使用java编写一个图形界面,包含姓名、学号、班级、性别、兴趣爱好,并且班级可以选择
时间: 2023-07-04 17:13:40 浏览: 167
以下是一个简单的Java图形界面程序,包含姓名、学号、班级、性别、兴趣爱好,并且班级可以选择:
```java
import javax.swing.*;
import java.awt.event.*;
public class StudentForm extends JFrame implements ActionListener {
private JLabel nameLabel, idLabel, classLabel, genderLabel, interestLabel;
private JTextField nameField, idField;
private JComboBox<String> classComboBox;
private JRadioButton maleRadioButton, femaleRadioButton;
private JCheckBox musicCheckBox, sportCheckBox, travelCheckBox;
private JButton submitButton;
public StudentForm() {
// 设置窗口标题和大小
setTitle("学生信息表单");
setSize(400, 300);
// 创建标签和文本框
nameLabel = new JLabel("姓名:");
nameField = new JTextField(20);
idLabel = new JLabel("学号:");
idField = new JTextField(20);
// 创建班级下拉框
classLabel = new JLabel("班级:");
String[] classes = {"1班", "2班", "3班", "4班", "5班"};
classComboBox = new JComboBox<String>(classes);
// 创建性别单选框
genderLabel = new JLabel("性别:");
maleRadioButton = new JRadioButton("男");
femaleRadioButton = new JRadioButton("女");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleRadioButton);
genderGroup.add(femaleRadioButton);
// 创建兴趣爱好复选框
interestLabel = new JLabel("兴趣爱好:");
musicCheckBox = new JCheckBox("音乐");
sportCheckBox = new JCheckBox("运动");
travelCheckBox = new JCheckBox("旅游");
// 创建提交按钮
submitButton = new JButton("提交");
submitButton.addActionListener(this);
// 创建面板并添加组件
JPanel panel = new JPanel();
panel.add(nameLabel);
panel.add(nameField);
panel.add(idLabel);
panel.add(idField);
panel.add(classLabel);
panel.add(classComboBox);
panel.add(genderLabel);
panel.add(maleRadioButton);
panel.add(femaleRadioButton);
panel.add(interestLabel);
panel.add(musicCheckBox);
panel.add(sportCheckBox);
panel.add(travelCheckBox);
panel.add(submitButton);
// 添加面板到窗口并显示窗口
add(panel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// 处理提交按钮的点击事件
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String id = idField.getText();
String className = (String) classComboBox.getSelectedItem();
String gender = maleRadioButton.isSelected() ? "男" : "女";
String interests = "";
if (musicCheckBox.isSelected()) {
interests += "音乐 ";
}
if (sportCheckBox.isSelected()) {
interests += "运动 ";
}
if (travelCheckBox.isSelected()) {
interests += "旅游";
}
JOptionPane.showMessageDialog(this, "姓名:" + name + "\n学号:" + id + "\n班级:" + className + "\n性别:" + gender + "\n兴趣爱好:" + interests);
}
public static void main(String[] args) {
new StudentForm();
}
}
```
运行上述代码,会弹出一个窗口,包含姓名、学号、班级、性别、兴趣爱好等控件,用户可以输入信息并点击提交按钮,程序会将输入的信息显示在对话框中。
阅读全文