用java语言写,编写GUI界面,模拟课堂随机点名器,在界面输入班级学生姓名(用逗号隔开)点击初始化后就可以开始多次随机点名,点名的结果会在文本区中显示。要求 (1)按钮1点击时不仅初始化名单而且会将之前显示点名结果的文本区清空。 (2)按钮2点击时会随机输出一个学生名字,并追加在之前的文本区内容末尾,用分号隔开。同一个班级下,每个学生只会被点到一次,如果全部点过一轮就提示“该班级已全部被点名”。
时间: 2024-03-18 08:42:02 浏览: 89
好的,我了解了您的要求。以下是Java语言编写的GUI界面代码,实现了课堂随机点名器功能:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class RandomPicker extends JFrame implements ActionListener {
private JTextField inputField;
private JTextArea outputArea;
private JButton initButton;
private JButton pickButton;
private ArrayList<String> students;
private ArrayList<String> pickedStudents;
public RandomPicker() {
super("课堂随机点名器");
setLayout(new BorderLayout());
// 输入区域
JPanel inputPanel = new JPanel(new FlowLayout());
inputPanel.add(new JLabel("班级学生姓名:"));
inputField = new JTextField(30);
inputPanel.add(inputField);
initButton = new JButton("初始化");
initButton.addActionListener(this);
inputPanel.add(initButton);
add(inputPanel, BorderLayout.NORTH);
// 输出区域
JPanel outputPanel = new JPanel(new BorderLayout());
outputArea = new JTextArea(10, 30);
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
outputPanel.add(scrollPane, BorderLayout.CENTER);
pickButton = new JButton("随机点名");
pickButton.addActionListener(this);
outputPanel.add(pickButton, BorderLayout.SOUTH);
add(outputPanel, BorderLayout.CENTER);
// 初始化
students = new ArrayList<String>();
pickedStudents = new ArrayList<String>();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == initButton) {
String input = inputField.getText();
students.clear();
pickedStudents.clear();
outputArea.setText("");
for (String name : input.split(",")) {
students.add(name.trim());
}
JOptionPane.showMessageDialog(this, "初始化成功!");
} else if (e.getSource() == pickButton) {
if (students.isEmpty()) {
JOptionPane.showMessageDialog(this, "请先初始化班级学生姓名!");
return;
}
if (pickedStudents.size() == students.size()) {
JOptionPane.showMessageDialog(this, "该班级已全部被点名!");
return;
}
String student = getRandomStudent();
outputArea.append(student + "; ");
pickedStudents.add(student);
}
}
private String getRandomStudent() {
String student;
do {
student = students.get(new Random().nextInt(students.size()));
} while (pickedStudents.contains(student));
return student;
}
public static void main(String[] args) {
RandomPicker picker = new RandomPicker();
picker.setVisible(true);
}
}
```
运行该程序,会弹出一个GUI界面,在界面中输入班级学生姓名,点击“初始化”按钮,即可初始化名单。点击“随机点名”按钮,会随机输出一个学生名字,并追加在之前的文本区内容末尾,用分号隔开。同一个班级下,每个学生只会被点到一次,如果全部点过一轮就提示“该班级已全部被点名”。
阅读全文