此項目的目標是創建兩個班級:學生班級和GUI班級。學生類包含姓名,地址,餘額和專業。我有學生和GUI類都創建我的問題是數組和循環。我需要讓Student類數組和相關的計數器變量成爲一個靜態變量,並且每當用戶輸入Student類(名稱,地址,平衡,主要)的信息時,它都會向JTextArea添加另一個Student對象。本質上,每次按下JButton時,JTextArea都會更新新學生的信息而不刪除舊信息。任何幫助,使這項工作將不勝感激!設計並實施能夠不斷接受輸入並創建多個學生對象的「學生」班
我的代碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Student {
private String name;
private String address;
private String balance;
private String major;
// Constructs fields
public Student(String name, String address, String balance, String major) {
this.name = name;
this.address = address;
this.balance = balance;
this.major = major;
}
public String setName(String Name) {
this.name = name;
return name;
}
public String setAddress(String address) {
this.address = address;
return address;
}
public String setBalance(String balance) {
this.balance = balance;
return balance;
}
public String setMajor(String major) {
this.major = major;
return major;
}
public String toString() {
return ("Name: " + this.name + " Address: " + this.address
+ " Balance: " + this.balance + " Major: " + this.major);
}
}
public class SecondAssignment extends JFrame implements ActionListener {
public SecondAssignment() {
setLayout(new GridLayout(6, 1, 1, 1));
// Creates TextField, TextArea, and button components
name = new JTextField();
address = new JTextField();
balance = new JTextField();
major = new JTextField();
JButton jbtSubmit = new JButton("Submit");
echoStudent = new JTextArea();
// Add TextField, TextArea, and button components to the frame
add(new JLabel("Name: "));
add(name);
add(new JLabel("Address: "));
add(address);
add(new JLabel("Balance: "));
add(balance);
add(new JLabel("Major: "));
add(major);
add(new JLabel("Submit Button: "));
add(jbtSubmit);
jbtSubmit.addActionListener(this);
add(echoStudent);
echoStudent.setEditable(false);
}
// TextFields
private JTextField name;
private JTextField address;
private JTextField balance;
private JTextField major;
// Echo TextArea
private JTextArea echoStudent;
// Listener
public void actionPerformed(ActionEvent a) {
Student student1 = new Student(name.getText(), address.getText(),
balance.getText(), major.getText());
echoStudent.setText(student1.toString());
}
public static void main(String[] args) {
SecondAssignment frame = new SecondAssignment();
frame.setTitle("Student Interface");
frame.setSize(500, 700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
你的意思是你想每次點擊提交按鈕時清除表單輸入文本?或者你想存儲所有的學生並將其全部顯示出來? – bagage
對不起,我不是很清楚。我的數組可以是一個50的靜態大小,可以存儲50個「學生」,而不必在按下按鈕後清除JTextArea。 – Ben
爲什麼你需要一個大小爲50的靜態數組而不是像一個簡單的List容器那樣的動態數組? – bagage