Skip to content

JTable becomes blank after executing update on table? [closed]

I am trying to write some software where when a user adds a new entry to a SQL database, my JTable showing the entries in the database updates. Currently, when the method updateTable(Object[][] data) is called, it results in the table becoming blank.

Would anyone know of a fix for this type of issue?

Here is the code for the method:

     * This method updates the JTable which shows the Amp Settings.
     * @param data A 2D Array of Objects witch represents the data in the
     * database.
    private void updateTable(Object[][] data)
        // A new DefaultTableModel.
        DefaultTableModel dtm = new DefaultTableModel();

        // Looping over the data, create a new row and add it to the DataModel.
        for (int i = 0; i < data.length; i++)
            Object[] row = new Object[data[i].length];

            // Fill the row's data.
            for (int j = 0; j < row.length; j++)
                row[j] = data[i][j];

            // Set the row in the table model.

        // Set the model of the table to the newly created DefaultTableModel.
        ((AbstractTableModel) table.getModel()).fireTableDataChanged();

Here is the code which calls updateTable():

// Calls update table, SERVER.dbtoArray() returns a 2D Array of objects.



DefaultTableModel dtm = new DefaultTableModel();

Even though you add data to the TableModel you didn’t add any column names so as far as the table is concerned there are 0 columns to display.

Your code should be something like:

String[] columnNames = { "Column1", "Column2", "..." );
DefaultTableModel dtm = new DefaultTableModel(columnNames, 0);

Or a better approach would be to use:

DefaultTableModel dtm = (DefaultTableModel)table.getModel();

This will keep the existing columns and just add the data.

Also you don’t need to recreate the row array. You already have the data as a row in your 2D array:

for (int i = 0; i < data.length; i++)
    Object[] row = data[i];
    model.addRow( row );
1 People found this is helpful