简体   繁体   中英

Pass LinkedList from another class for JTable. Automatically update table

So, I am currently building the GUI for my program. I am using JTables with a custom AbstractTableModel to fill them with the contents of my different LinkedLists. However, if I add a JTable to my GUI class, and initialize the LinkedList class there, then that is not the LinkedList that I need. I need the LinkedList Studentlist, which I have stored in my Database class. How do I tell the table that? I can't really show any GUI code, because it is all still in the making, and I am just testing things out at the moment.

My other question is, this is my AbstractTableModel:

public class StudentTableModel extends AbstractTableModel {

public static final String[] columnNames = { "ID", "First Name",
        "Last Name" };
private LinkedList<Student> data;

public StudentTableModel(LinkedList<Student> data) {
    this.data = data;
}

@Override
public int getColumnCount() {
    return columnNames.length;
}

@Override
public String getColumnName(int column) {
    return columnNames[column];
}

@Override
public int getRowCount() {
    return data.size();
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    Student student = data.get(rowIndex);
    if (student == null) {
        return null;
    }
    switch (columnIndex) {
    case 0:
        return student.getID();
    case 1:
        return student.getFirstname();
    case 2:
        return student.getLastname();
    default:
        return null;
    }
}

}

Do I need to add anything to the code to make the table automatically update when a student is added to the list?

Thanks in advance.

At a minimum,

  • As shown here , you implementation of setValueAt() must fire an event appropriate to your update.

  • If you expose a public method to mutate data , it too must fire an appropriate event.

In this context, appropriate means one of the fireXxx() methods inherited from AbstractTableModel .

Do I need to add anything to the code to make the table automatically update when a student is added to the list?

Create a method in the TableModel such that when the Student is added then pass the Student object to the list and add it to the list. Since you are using AbstractTableModel you need to fire appropriate events after data change.

private void addStudent(Student student) {
    data.add(student);
    fireTableDataChanged();
}

if I add a JTable to my GUI class, and initialize the LinkedList class there, then that is not the LinkedList that I need. I need the LinkedList Studentlist, which I have stored in my Database class.

While you are creating table model then query for the StudentList and send that list to the table model constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM