Java 向 JTable 添加行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/295649/
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
Adding rows to a JTable
提问by Saiyine
We have a simple project where we read data from a socket and we want to populate a table with the coming data, but we can't find a way to add rows to a yet created JTable
object, we can only find how to add rows at creation time of the table.
我们有一个简单的项目,我们从套接字读取数据,我们想用即将到来的数据填充一个表,但是我们找不到向尚未创建的JTable
对象添加行的方法,我们只能找到如何添加行表的创建时间。
Is it possible to add rows dynamically to a JTable
, or there is a better alternative object to deal with this way of showing data?
是否可以将行动态添加到 a JTable
,或者有更好的替代对象来处理这种显示数据的方式?
EDIT: Thanks a lot for your answers.
编辑:非常感谢您的回答。
All three of them look very promising, but I have to choose only one and I think the best is Guillaume's.
他们三个看起来都很有前途,但我只能选择一个,我认为最好的是纪尧姆的。
采纳答案by Guillaume
You should create a custom TableModel
. A JTable
doesn't actually store the rows, it always delegates that to a TableModel
. To help you implementing it, you should make use of AbstractTableModel
. Don't forget to call fireTableRowsInserted()
every time you add rows. For better performances if you add a lot of rows, try to batch the updates and add many rows at a time.
您应该创建一个自定义TableModel
. AJTable
实际上并不存储行,它总是将其委托给 a TableModel
。为了帮助您实现它,您应该使用AbstractTableModel
. fireTableRowsInserted()
每次添加行时不要忘记调用。如果添加很多行,为了获得更好的性能,请尝试批量更新并一次添加多行。
回答by Paul Tomblin
Once you start dynamically adding and removing elements from a JTable, you really need to start using a TableModel.
一旦开始在 JTable 中动态添加和删除元素,您就真的需要开始使用 TableModel。
See the Java Tutorialfor more details.
有关更多详细信息,请参阅Java 教程。
回答by Peter
If you use the default table model for a JTable then you can add rows with following code
如果您对 JTable 使用默认表模型,则可以使用以下代码添加行
if ( dest+1 < table.getRowCount()-1 )
( (DefaultTableModel) table.getModel() ).insertRow(dest+1, getValuesForNewRow());
else
( (DefaultTableModel) table.getModel() ).addRow(getValuesForNewRow());