Tilen Kavčič
Tilen Kavčič

Reputation: 121

Refreshing JTable after changing data

I want to refresh and display my JTable after a user pressed a button. Before that the button generates an Object[][] in which the filtered data from the table is held. The filtered data is different only in the number of rows.

I'm using the netbeans UI creator and the only way I could populate the table with data is by defining the abstractTableModel. Here is the code of my abstractTableModel:

class myTable extends AbstractTableModel{
    private String[] stolpci = {"Kategorija","Podkategorija","Opis","Cena","Datum","Boni"};
    private Object[][] data = PregledovalnikGUI.vrniTabelo(); /*PregledovalnikGUI.vrniTabelo() returns a value in form of Object[][] in which the data is held*/
    public int getColumnCount() {
        return stolpci.length;
    }
    public int getRowCount() {
        return vrstice.length;
    }
    public String getColumnName(int col) {
        return stolpci[col];
    }
    public Object getValueAt(int row, int col) {
        return vrstice[row][col];
    }
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }
    public void setValueAt(Object value, int row, int col) {
        vrstice[row][col] = value;
        fireTableCellUpdated(row, col);
    }

The jTable is set like:

Tabela.setModel(new myTable());

Which methods do I need to define to get the table to refresh at runtime?

Upvotes: 1

Views: 19449

Answers (2)

Sionnach733
Sionnach733

Reputation: 4736

inside myTable you could have a method called refresh() something like this

public void refresh(Object[][] objects){
    //make the changes to the table, then call fireTableChanged
    fireTableChanged(null);
}

Then in the button listener, call the above method:

Tablea.refresh(objects);//objects stores your filtered data

Upvotes: 3

MadProgrammer
MadProgrammer

Reputation: 347184

If you create a new TableModel, then nothing, the table will automatically update itself.

If the underlying data of the model is changed, then from within the model (seen as you extending from AbstractTableModl), you could call fireTableDataChanged, which lets the table know that the contents of the table have changed and it should redraw itself.

This may require that the model either have a refresh method of its own or that it has the capability to listen to changes from the data it is modelling

Upvotes: 3

Related Questions