Josh
Josh

Reputation: 828

Update a JTable with setValueAt

I have a JTable that is created from an AbstractTableModel. I am successfully initialising the table on the screen. (it is an informational table only - clicks are disabled) When i call setValueAt from the JTable object nothing happens.

Any help is much appreciated! Thanks in advance.

public void initialiseAuxDataStructure(TableModel table) {
    JTable auxDS = new JTable(table);
    Font f = auxDS.getFont();
    auxDS.setFont(new Font(f.getFontName(), f.getStyle(), f.getSize()+2));
    auxDS.setFocusable(false);
    auxDS.setRowSelectionAllowed(false);

    JTableHeader header = auxDS.getTableHeader();
    f = header.getFont();
    header.setFont(new Font(f.getFontName(), Font.BOLD, f.getSize()+2));

    pnlCenter.add(new JScrollPane(auxDS), BorderLayout.CENTER);
    pnlCenter.revalidate();

}

public void updateTable(String value, int row, int col) {
    auxDS.setValueAt(value, row, col);
    auxDS.revalidate();
}

and the abstract table model is:

public class TableModel extends AbstractTableModel {

private String[] columnNames;
private Object[][] data;

public TableModel(String[] columnNames, int columns) {
    this.columnNames = columnNames;
    data = new Object[columns][columnNames.length];
    for (int i=0; i<columns;i++) {
        data[i][0] = i;
    }
}

public TableModel(String[] colNames, Object[][] startData){
    this.columnNames = colNames;
    this.data = startData;
}

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

public int getRowCount() {
    return data.length;
}

public String getColumnName(int col) {
    return columnNames[col];
}

public Object getValueAt(int row, int col) {
    return data[row][col];
}

}

Upvotes: 0

Views: 6279

Answers (1)

camickr
camickr

Reputation: 324098

I gave you the answer in my comment.

You didn't implement the setValueAt() method so nothing happens.

You can read the JTable API and follow the link to the Swing tutorial on How to Use Tables where you will find a simple implementation.

Or you can use the DefaultTableModel which already does this for you.

Upvotes: 4

Related Questions