Java(2)编写程序实现:通过文本行输人学生姓名,通过单选按钮选择性别,通过复选框选择课程,并在文本框中显示所填写及选择的信息。请自行安排版面,使其美观。(30分)
时间: 2024-12-29 09:32:32 浏览: 3
在Java中,你可以使用Swing库来创建图形用户界面(GUI),并结合Scanner类获取用户输入。以下是一个简单的示例程序来实现这个需求:
```java
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class StudentInfoForm extends JFrame {
private JLabel nameLabel;
private JTextField nameField;
private JRadioButton maleButton, femaleButton;
private JCheckBox mathCheck, scienceCheck, englishCheck;
private JTextArea resultArea;
public StudentInfoForm() {
setTitle("学生信息录入");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 布局管理器
setLayout(new GridBagLayout());
// 创建组件
nameLabel = new JLabel("姓名:");
nameField = new JTextField();
maleButton = new JRadioButton("男");
femaleButton = new JRadioButton("女");
maleButton.setSelected(true); // 默认设置为男性
mathCheck = new JCheckBox("数学");
scienceCheck = new JCheckBox("科学");
englishCheck = new JCheckBox("英语");
resultArea = new JTextArea(5, 20);
resultArea.setEditable(false); // 阻止用户编辑
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1;
add(nameLabel, gbc);
gbc.gridy++; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0;
add(nameField, gbc);
gbc.gridy++;
add(new JLabel("性别:"), gbc);
gbc.gridy++;
gbc.weightx = 0; // 设置单选按钮宽度固定
add(maleButton, gbc);
add(femaleButton, gbc);
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
JPanel coursesPanel = new JPanel(); // 使用FlowLayout布局复选框
coursesPanel.setLayout(new FlowLayout());
coursesPanel.add(mathCheck);
coursesPanel.add(scienceCheck);
coursesPanel.add(englishCheck);
add(coursesPanel, gbc);
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
add(new JScrollPane(resultArea), gbc); // 显示结果
pack();
// 获取用户输入并更新结果显示
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学生姓名:");
String name = scanner.nextLine();
resultArea.append("姓名: " + name + "\n");
if (maleButton.isSelected()) {
resultArea.append("性别: 男\n");
} else {
resultArea.append("性别: 女\n");
}
for (JCheckBox check : Arrays.asList(mathCheck, scienceCheck, englishCheck)) {
if (check.isSelected()) {
resultArea.append(check.getText() + " 已选择\n");
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(StudentInfoForm::new);
}
}
```
阅读全文