在 Java 中将数组添加到 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6899151/
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-30 17:50:09  来源:igfitidea点击:

Adding an Array to JTable in Java

javaarraysuser-interfacejtablerow

提问by Jonas

Since you create the JTablewith an matrix for data and array for the columns I figured there should be a way to after created the JTableadding an array (row). Or how is it meant to add a row with Strings?

由于您JTable为数据创建了矩阵,为列创建了数组,我认为应该有一种方法可以在创建后JTable添加数组(行)。或者用字符串添加一行是什么意思?

Thanks!

谢谢!

回答by S.L. Barth - Reinstate Monica

You cannot add to a JTable directly, you have to get the underlying TableModel. You get this by calling JTable.getModel(). TableModel is an interface, in a standard JTable it's implementation is DefaultTableModel. So you have to cast the underlying TableModel to a DefaultTableModel, and then you can apply DefaultTableModel.addRow( Object[] ). (You do, of course, check that the cast is safe and all that).

您不能直接添加到 JTable,您必须获得底层的 TableModel。您可以通过调用JTable.getModel(). TableModel 是一个接口,在标准 JTable 中它的实现是 DefaultTableModel。因此,您必须将底层 TableModel 强制转换为 DefaultTableModel,然后才能应用DefaultTableModel.addRow( Object[] ). (当然,您确实要检查演员表是否安全等等)。

回答by aioobe

To change the data displayed by the JTable, you need to go through the TableModel.

要更改 显示的数据JTable,您需要通过TableModel

Have a look at the JTable.getModel()method and the methods in the TableModelinterface.

看看JTable.getModel()方法和TableModel接口中的方法。

回答by Pratik

you can add/insert row in JTable like this way

您可以像这样在 JTable 中添加/插入行

table.getModel().insertRow(table.getRowCount(),new Object[]{"hello","50"});

here is the tutorial link

这是教程链接

http://www.roseindia.net/java/example/java/swing/InsertRows.shtml

http://www.roseindia.net/java/example/java/swing/InsertRows.shtml

回答by mKorbel

there aren't some problem with that, here is How to Use Tableswith nice example, tons of examples hereand here

没有什么问题,这里是如何使用表格和很好的例子,这里这里有大量的例子

回答by Dame Lyngdoh

You can also create a class of your own which extends AbstractTableModeland implement the abstract methods. This class can also contain the array (or whichever collection or data structure you use) and the abstract methods which you implement will use this array, methods such as getValueAtand setValueAt. Then you can create a new instance of this class and set the table model of the table to this object. Adding rows to this table is now possible by adding entries/elements to the array.

您还可以创建自己的类,它扩展AbstractTableModel并实现抽象方法。此类还可以包含数组(或您使用的任何集合或数据结构),您实现的抽象方法将使用此数组,如getValueAtsetValueAt等方法。然后就可以新建这个类的实例,将表的表模型设置为这个对象。现在可以通过向数组添加条目/元素来向该表添加行。