Hugh Macdonald
Hugh Macdonald

Reputation: 143

Syncing a JTable with ArrayList of Objects values in Java

My program has a JTable which displays information about a student. e.g.

Columns contain: "Name", "Surname", "Age", "Year"

I also have an Object class for students as follow:

public class Student {
    private final String name;
    private final String surname;
    private final int age;
    private int year;

    public Student(String name, String surname, int age, int year) {
        this.name = name;
        this.surname = surname;
        this.age = age;
        this.year = year;
    }

    public String getName() {
        return this.name;
    }

    public String getSurname() {
        return this.surname;
    }

    public int getAge() {
        return this.age;
    }

    public int getYear() {
        return this.year;
    }

    public void setYear(int i) {
        this.year = i;
    }
}

I have a StudentManager below:

public class StudentManager {
    private static ArrayList<Student> students = new ArrayList<Student>();

    public static void addStudent(Student obj) {
        this.students.add(obj);
    }

    public static void removeStudent(Student obj) {
        this.students.remove(obj);
    }

    public static Student getStudentByName(String n) {
        for(Student s : this.students) {
            if(s.getName() == n)
                return s;
        }
        return null;
    }
}

What i want to know:

I want it so that when i change a value in the student class object the JTable will update with the new information.

I also want the JTable to remove the row of a student if I was to remove a Student class object from my ArrayList.

Also the same with adding a Student, I want it to add a row to the JTable with the students Name, Surname, Age and Year.

Upvotes: 1

Views: 227

Answers (1)

lopisan
lopisan

Reputation: 7830

You need to create a StudentTableModel (which extends AbstractTableModel) that will supply data for the JTable and when some change occures it will fire updates (fire* methods).

Next, the StudentTableModel needs to know that some change occured. I would use PropertyChangeListener for that. See PropertyChangeSupport to see how it is used.

Basically, your StudentTableModel will listen to changes from StudentManager and each Student and it will propagate the updates to JTable.

Alternative ways:

  • You can use Observable/Observer instead of PropertyChangeListener
  • You can merge functionality of StudentTableModel and StudentManager

Upvotes: 1

Related Questions