"I cannot get my JTable to update with a new row unless I restart the program."
I think what you're expecting is that when the database table update, so should your JTable
. It doesn't really work like that. You need to update the TableModel
, and the JTable
will be automatically updated
Since resultSetToTableModel
returns a DefuaultTableModel
, you can use either of the two methods from DefaultTableModel
:
public void addRow(Object[] rowData)
- Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.public void addRow(Vector rowData)
- Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So when your are adding the data to the database, you also want to update the DefaultTableModel
like this
public static void addGenre(Integer a, String b){
...
rowsAdded = stmt.executeUpdate(query);
if (rowsAdded > 0) {
DefaultTableModel model = (DefaultTableModel)tab1.getModel();
model.addRow( new Object[] { a, b });
}
}
Also noticed I changed the method signature to Integer
instead of int
so it will fit with the Object[]
passed to addRow
. The int
you pass to it will get autoboxed to Integer
SIDE NOTES
Don't swallow you exception by putting nothing in the
catch
block. Put something meaningful that will notify you of any exceptions that may occur, likecatch(Exception ex) { ex.printStackTrace(); }
You should also
close
yourConnection
s,Statement
s, andResultSet
sYou should use
PreparedStatement
instead ofStatement
, to avoid SQL injection.