用Java编写类ExamFive,实现创建一个窗体,窗体的标题为考生学号(如2201101)。在第一个文本框输入一个年份,单击“判断”按钮后,在第二个文本框中输出该年是否是闰年的信息;单击“清空”按钮后,将两个文本框的内容清空。的代码
时间: 2024-11-29 19:18:37 浏览: 30
在Java中,我们可以使用Swing库来创建图形用户界面(GUI)。下面是一个简单的`ExamFive`类的示例,它包含了两个JTextField(文本框)和两个JButton(按钮),用于输入年份、判断闰年以及清空内容:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ExamFive extends JFrame {
private JTextField yearInput;
private JTextField resultOutput;
private JButton judgeButton;
private JButton clearButton;
public ExamFive() {
// 设置窗口标题
setTitle("考生学号:(未填写)");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建组件
yearInput = new JTextField();
resultOutput = new JTextField();
judgeButton = new JButton("判断");
clearButton = new JButton("清空");
// 添加事件监听器
judgeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String year = yearInput.getText();
if (isLeapYear(year)) {
resultOutput.setText(year + " 是闰年");
} else {
resultOutput.setText(year + " 不是闰年");
}
}
});
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
yearInput.setText("");
resultOutput.setText("");
}
});
// 布局管理
setLayout(new GridLayout(3, 2));
add(new JLabel("请输入年份:"));
add(yearInput);
add(judgeButton);
add(new JLabel("结果:"));
add(resultOutput);
add(clearButton);
// 展示窗口
setVisible(true);
}
// 判断闰年的辅助函数
private boolean isLeapYear(String yearStr) {
int year = Integer.parseInt(yearStr);
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ExamFive();
}
});
}
}
```
阅读全文
相关推荐


















