Confused by JTable addRow

huangapple go评论75阅读模式
英文:

Confused by JTable addRow

问题

关于向JTable添加行,我在这个问题的答案中找到了有用的信息<https://stackoverflow.com/questions/3549206/how-to-add-row-in-jtable>。

对于这段代码,我有点困惑:

DefaultTableModel model = (DefaultTableModel) jtable.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});

JTable已经使用表格模型设置好了。我对代码的第一行的理解是,它将DefaultTableModel model(我们称之为newmodel)与表格中的model关联,并且这个newmodel没有附加到表格上(因为没有使用setModel()将其设置到表格上)。

那么,如何通过这个newmodel执行的addRow方法将新行插入到Jtable中呢?

英文:

Regarding adding row to JTable, I found this useful answers for this question <https://stackoverflow.com/questions/3549206/how-to-add-row-in-jtable>.

I am confusing a little bit about this code:

DefaultTableModel model = (DefaultTableModel) jtable.getModel();
model.addRow(new Object[]{&quot;Column 1&quot;, &quot;Column 2&quot;, &quot;Column 3&quot;});

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?

答案1

得分: 1

因为现在 model 引用的是已经与表格关联的模型,你是通过 (DefaultTableModel) jtable.getModel() 获取它的。它已经存在了,你不需要显式地为表格分配一个模型(如果你遵循链接问题中的说法,你在构造函数中已经做过了)。

你没有替换它,你只是在现有的模型上操作。而且你不需要重新设置它到表格上,因为你从未取消它。你只是在模型本身上操作。

英文:

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.

huangapple
  • 本文由 发表于 2020年7月29日 18:04:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63151137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定