To store your students, you can do it either statically (using a array with a fixed size) or dynamically (using a collection such as a List
).
In both ways, your SecondAssignment class will need to store this element and fill in with the created students.
Static way
If you need a static array of size 50, simply declare it with:
private Student[] myStudents = new Student[50];
private int currentIndice = 0;
Then in action performed, you can save your student:
public void actionPerformed(ActionEvent a) {
Student student1 = new Student(name.getText(), address.getText(),
balance.getText(), major.getText());
//check that we have still room in the array
if (currentIndice < 50) {
myStudents[currentIndice] = student1;
// increase indice to the next available element
++currentIndice;
}
//otherwise handle error
else {
//some error management
}
echoStudent.setText(student1.toString());
}
Major drawback of this solution is that your array has a fixed size and thus you cannot handle more than 50 students.
Dynamic way
Instead, you can add element to a collection that will increase from time to time. First import packages:
import java.util.ArrayList;
import java.util.List;
Then declare your List:
private List<Student> myStudents = new ArrayList<>;
And in your actionPerformed
method:
public void actionPerformed(ActionEvent a) {
Student student1 = new Student(name.getText(), address.getText(),
balance.getText(), major.getText());
//simply add the new student to the list
myStudents.add(student1);
echoStudent.setText(student1.toString());
}
You can retrieve the number of students with myStudents.size()
, and benefit from collection features (remove from list, search in list, etc.).
Edit
As Nick Rippe stated, if echoStudent label must handle the list of all students, the simpler way would be to keep the current text instead of resetting each time: replacing echoStudent.setText(student1.toString());
with echoStudent.setText(echoStudent.getText() + "\n" + student1.toString());
would do the job for example (\n
is escape sequence for a new line).