Search code examples
javaswingjtableabstracttablemodel

Issue with fireTableDataChanged()


I am almost finished creating a program in Java using Eclipse that uses a JTable. What I did was a made the JTable, associated it with a class that extends AbstractTableModel that I called ResultsTableModel, and made a method called refresh that used the method fireTableDataChanged(). The class looks like this:

public class ResultPanel extends JPanel {

ResultsTableModel rm;
JTable table;
public ResultPanel() {
    rm = new ResultsTableModel();
    table = new JTable();

    setLayout(new BorderLayout());

    add(new JScrollPane(table), BorderLayout.CENTER);
}

public void setData(List<Entry> entries) {
    rm.setData(entries);
}

public void refresh() {
    rm.fireTableDataChanged();
}

}

The problem is that when I run the program, which calls the refresh() method at some point, the table data doesn't refresh, in fact, the table isn't even shown at all. Here is the class were I construct the table model:

public class ResultsTableModel extends AbstractTableModel {

private List<Entry> entries = new ArrayList<Entry>();

private String[] colNames = {"STATUS", "ROOT", "DEFINITION"};


public void setData(List<Entry> list) {
    this.entries = list;
}

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


@Override
public int getColumnCount() {
    return 3;
}

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

@Override
public Object getValueAt(int arg0, int arg1) {
    Entry entry = entries.get(arg0);

    switch(arg1) {
    case 0:
        return entry.getStatus();
    case 1:
        return entry.getRoot();
    case 2:
        return entry.getDef();
    default:
        return "Invalid index";
    }
}

}

This is just about the best description I can give of the problem I have. No exceptions are being thrown by the program, it just isn't showing the table event though I called the setVisible(true); method on it. Any help would be greatly appreciated, thank you.


Solution

  • Your never telling your JTable to actually contain the created TableModel.

    You can pass it via the constructor:

    rm = new ResultsTableModel();
    table = new JTable(rm);
    

    Additionally, I'd recommend invoking the fireTableDataChanged() only from within your ResultsTableModel class (e.g. in the end of the setData() method) and not explicitly from your view (JPanel). The whole point of having a TableModel is to separate your view from the model.