JAVA 设计一个Student类并编写代码,Student类的属性有姓名,出生年、月、日;自定义的方法:至少包括计算学生年龄的方法calAge()。编写一个GUI类,输入学生的姓名和出生年、月、日,由此创建这个Student对象,调用Student类的方法calAge(),计算出该学生的年龄,并将年龄显示在用户界面上。(大致界面如下,是否加背景、是否使用滚动窗格自行决定。)
时间: 2024-02-15 09:04:13 浏览: 190
编写一个JAVA程序,定义一个Student类
5星 · 资源好评率100%
下面是Java实现代码:
```java
import java.time.LocalDate;
import java.time.Period;
public class Student {
private String name;
private LocalDate birthDate;
public Student(String name, int year, int month, int day) {
this.name = name;
this.birthDate = LocalDate.of(year, month, day);
}
public int calAge() {
LocalDate currentDate = LocalDate.now();
Period period = Period.between(birthDate, currentDate);
return period.getYears();
}
public String getName() {
return name;
}
}
```
```java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class StudentGUI extends JFrame {
private JTextField nameField;
private JTextField yearField;
private JTextField monthField;
private JTextField dayField;
private JLabel ageLabel;
public StudentGUI() {
setTitle("学生年龄计算器");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建输入框和标签
nameField = new JTextField(10);
yearField = new JTextField(4);
monthField = new JTextField(2);
dayField = new JTextField(2);
ageLabel = new JLabel("请填写学生信息");
// 创建按钮
JButton calAgeButton = new JButton("计算年龄");
calAgeButton.addActionListener(new CalAgeListener());
// 添加组件到面板
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(new JLabel("姓名:"));
panel.add(nameField);
panel.add(new JLabel("出生年月日:"));
JPanel birthPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
birthPanel.add(yearField);
birthPanel.add(new JLabel("年"));
birthPanel.add(monthField);
birthPanel.add(new JLabel("月"));
birthPanel.add(dayField);
birthPanel.add(new JLabel("日"));
panel.add(birthPanel);
panel.add(calAgeButton);
panel.add(ageLabel);
add(panel);
}
// 计算年龄按钮的监听器
private class CalAgeListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
int year = Integer.parseInt(yearField.getText());
int month = Integer.parseInt(monthField.getText());
int day = Integer.parseInt(dayField.getText());
Student student = new Student(name, year, month, day);
int age = student.calAge();
ageLabel.setText("学生" + name + "的年龄是" + age + "岁");
}
}
public static void main(String[] args) {
StudentGUI gui = new StudentGUI();
gui.setVisible(true);
}
}
```
运行程序后,会弹出一个图形用户界面,用户可以输入学生的姓名和出生年、月、日。点击“计算年龄”按钮后,程序会创建一个Student对象,并调用calAge()方法计算出学生的年龄。最后,年龄会显示在界面上。
阅读全文