java 如何更新 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2732865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:35:52  来源:igfitidea点击:

how to Update JTable

javaswingjtable

提问by Eddinho

Good evening

晚上好

I have a JTable that I built with a TableModel how to update the elements of the table, because when I do table = new JTable (new TableProg (elementTab)) I create another table above the original table and it is very ugly

我有一个用 TableModel 构建的 JTable 如何更新表的元素,因为当我执行 table = new JTable (new TableProg (elementTab)) 时,我在原始表上方创建了另一个表,它非常难看

So for example how to update element of table in a loop at each iteration as "elementTab" changes?

因此,例如如何在每次迭代时在“elementTab”更改时更新循环中的表元素?

thank you very much

非常感谢你

回答by camickr

Not sure I understand your question.

不确定我理解你的问题。

To update the cells of a table you just use

要更新您刚刚使用的表格的单元格

table.setValueAt(...);

To update the entire table at once you can create a new TableModel and then update the table with the new model:

要一次更新整个表,您可以创建一个新的 TableModel,然后使用新模型更新表:

TableModel model = new YourTableModel(...);
table.setModel( model );

While learning how to use models start with the DefaultTableModel since it also support dynamic changes to the model by using addRow(...) and removeRow().

在学习如何使用模型时,从 DefaultTableModel 开始,因为它还支持使用 addRow(...) 和 removeRow() 对模型进行动态更改。

回答by Jonas

I recommend you to extend an AbstractTableModeland implement an void addRow(YourObject row)that fits you. Or if you want to update the hole tables data, you could implement an void addElements(YourCollection elements)and use the void fireTableDataChanged()-method.

我建议你扩展一个AbstractTableModel并实现一个void addRow(YourObject row)适合你的。或者,如果您想更新孔表数据,您可以实现void addElements(YourCollection elements)并使用void fireTableDataChanged()- 方法。

I.e. keep your data in a LinkedListand don't forget to use void fireTableRowsInserted(int firstRow, int lastRow)when you add a new row.

即,将您的数据保存在 a 中,LinkedList并且void fireTableRowsInserted(int firstRow, int lastRow)在添加新行时不要忘记使用。

回答by Eddinho

Thanks you so much everyone i solved my probleme with :

非常感谢大家,我解决了我的问题:

model = new TableProg(elements); table.setModel(model);

模型 = 新表程序(元素);table.setModel(模型);

in the loop

在循环

回答by missionE46

A little more details on what elementTab is would be very helpful in suggesing a solution. If you want to add rows, simply create an array of objects and add to the model. Eg.

关于 elementTab 是什么的更多细节对于提出解决方案非常有帮助。如果要添加行,只需创建一个对象数组并添加到模型中即可。例如。

    TableModel model = table.getModel();
Object[] row = new Object[] {1,2,3};
model.addRow(row);

if you want to selective update cells, use model.setValueAt(Object,row,col);

如果要选择性更新单元格,请使用 model.setValueAt(Object,row,col);