Regarding adding row to JTable
, I found this useful answers for this question How to add row in JTable?.
I am confusing a little bit about this code:
DefaultTableModel model = (DefaultTableModel) jtable.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
The JTable
was already set with a table model. My understanding in the first line of code is that it assigns the DefaultTableModel model
(lets call newmodel
) with the model
from table, and this newmodel
does not attach to the table (because it is not set to table using setModel()
).
So how can the addRow
method performed by this newmodel
insert new row to Jtable
?
Because now model
refers to the model already linked to the table, which you're getting via (DefaultTableModel) jtable.getModel()
. It's already there, you don't need to explicitly assign one to the table (you did it in the constructor, if you're following what the linked question says).
You're not substituting it, you're acting on the existing one. And you don't need to re-set it to the table, because you never unset it. You're just working on the model itself.