英文:
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[]{"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
?
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论