利用Swing包中实现简单学生信息GUI
时间: 2024-02-01 17:03:24 浏览: 73
基于Java的图形用户界面文档
4星 · 用户满意度95%
好的,我可以为你提供一个简单的Swing GUI程序,用来存储和显示学生的信息。下面是代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class StudentGUI extends JFrame implements ActionListener {
private JTextField nameField, idField, majorField;
private JTextArea outputArea;
private JButton addButton, displayButton;
private ArrayList<Student> students;
public StudentGUI() {
students = new ArrayList<>();
// 设置窗口属性
setTitle("学生信息管理系统");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建组件
nameField = new JTextField();
idField = new JTextField();
majorField = new JTextField();
outputArea = new JTextArea();
addButton = new JButton("添加学生");
displayButton = new JButton("显示所有学生");
// 添加组件
JPanel inputPanel = new JPanel(new GridLayout(3, 2));
inputPanel.add(new JLabel("姓名:"));
inputPanel.add(nameField);
inputPanel.add(new JLabel("学号:"));
inputPanel.add(idField);
inputPanel.add(new JLabel("专业:"));
inputPanel.add(majorField);
JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
buttonPanel.add(addButton);
buttonPanel.add(displayButton);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(inputPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(new JScrollPane(outputArea), BorderLayout.EAST);
add(mainPanel);
// 监听按钮点击事件
addButton.addActionListener(this);
displayButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
// 添加学生
String name = nameField.getText();
String id = idField.getText();
String major = majorField.getText();
Student student = new Student(name, id, major);
students.add(student);
outputArea.append("添加学生:" + student.toString() + "\n");
} else if (e.getSource() == displayButton) {
// 显示所有学生
outputArea.setText("");
for (Student student : students) {
outputArea.append(student.toString() + "\n");
}
}
}
public static void main(String[] args) {
StudentGUI gui = new StudentGUI();
gui.setVisible(true);
}
}
class Student {
private String name;
private String id;
private String major;
public Student(String name, String id, String major) {
this.name = name;
this.id = id;
this.major = major;
}
@Override
public String toString() {
return "姓名:" + name + ",学号:" + id + ",专业:" + major;
}
}
```
上面的程序创建了一个简单的学生信息管理系统GUI界面,包含三个输入框用于输入学生的姓名、学号和专业,添加学生和显示学生信息的按钮,以及一个文本区域用于显示添加的学生信息或者显示所有学生信息。你可以参考这个程序,自己编写一个类似的界面,来存储和显示学生的信息。
阅读全文