0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
B.Green
  • 67
  • 7

1 Answers1

1

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.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Thank you very much, I think I get the point. My original thought this was **Pass-by-value**, meaning the ```model``` now is completely new one containing the **value** of ```jtable.getmodel()```. By what you say, I understand this is somewhat similar to **Pass-by-reference** thing, the ```model``` now holds reference to model of the table, and by changing this ```model``` changes the model of the table too. – B.Green Jul 30 '20 at 04:20