用java生成一个窗口,包含姓名 学号 班级 性别 兴趣爱好,确定按钮和取消按钮
时间: 2024-12-12 14:24:03 浏览: 14
在Java中,你可以使用Swing库来创建一个GUI窗口,它包含了各种组件如JLabel、JTextField、JButton等来显示信息并处理用户输入。下面是一个简单的例子展示如何创建这样一个包含姓名、学号、班级、性别和兴趣爱好的窗口,并附带确定和取消按钮:
```java
import javax.swing.*;
import java.awt.*;
public class StudentWindow extends JFrame {
private JLabel nameLabel;
private JTextField nameField;
private JLabel idLabel;
private JTextField idField;
private JLabel classNameLabel;
private JTextField classNameField;
private JLabel genderLabel;
private JComboBox<String> genderBox; // 假设这里性别选择有预设选项
private JLabel hobbyLabel;
private JTextArea hobbyArea;
private JButton confirmBtn;
private JButton cancelBtn;
public StudentWindow() {
setTitle("学生信息录入");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// 姓名、学号、班级
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
nameLabel = new JLabel("姓名:");
nameField = new JTextField(15);
mainPanel.add(nameLabel, gbc);
gbc.gridy++;
mainPanel.add(nameField, gbc);
// 类似地添加其他字段
// 性别
gbc.gridy++;
genderLabel = new JLabel("性别:");
genderBox = new JComboBox<>(new String[]{"男", "女"}); // 添加预设选项
mainPanel.add(genderLabel, gbc);
gbc.gridy++;
mainPanel.add(genderBox, gbc);
// 兴趣爱好
gbc.gridy++;
hobbyLabel = new JLabel("兴趣爱好:");
hobbyArea = new JTextArea();
hobbyArea.setRows(4);
hobbyArea.setColumns(30);
mainPanel.add(hobbyLabel, gbc);
gbc.gridy++;
mainPanel.add(hobbyArea, gbc);
// 按钮
gbc.gridy++;
confirmBtn = new JButton("确定");
cancelBtn = new JButton("取消");
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainPanel.add(confirmBtn, gbc);
gbc.gridy++;
mainPanel.add(cancelBtn, gbc);
setContentPane(mainPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new StudentWindow();
});
}
}
阅读全文