Search code examples
javaswingjtable

When adding a row to a JTable all of my columns disappear


I am working on this swing GUI and I ran into a problem with my program, when I try to add a row to a DefaultTableModel and then set the JTables model to the DefaultTableModel the columns end up deleting. I have two columns both have editable enabled, the columns also hold object values. There is nothing in my code which instructs to delete all of the columns.

This is my code: it runs into no errors.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    outputModel = new DefaultTableModel();
    outputModel.addRow(new Object[]{"hello","goodbye"});
    output.setModel(outputModel);
    System.out.println(output.getColumnCount());
    System.out.println(output.getRowCount());
}

The output is:

0
1

Both columns were deleted and one row was made. I am using Netbeans 11.2


Solution

  • outputModel = new DefaultTableModel();
    outputModel.addRow(new Object[]{"hello","goodbye"});
    output.setModel(outputModel);
    

    Don't keep creating a new DefaultTableModel and resetting the model. You need to add the row to the existing TableModel.

    So the code should be something like:

    DefaultTableModel model = (DefaultTableModel)output.getModel();
    model.addRow(new Object[]{"hello","goodbye"});