0

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319

1 Answers1

2

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.

Community
  • 1
  • 1
Carsten
  • 2,047
  • 1
  • 21
  • 46
  • Thank you so much, I think that fixed my problem! – James McGivern Aug 25 '15 at 02:12
  • 2
    (1+) @JamesMcGivern, ` I think that fixed my problem!` - don't forget to "accept' the answer by clicking on the check mark so people know the problem has been solved. Also, I hope you moved the fireTableDataChanged() method into the TableModel. a `fireXXX()` method should NEVER be invoked outside the TableModel. – camickr Aug 25 '15 at 02:52