java JTable - 如何将对象添加到表中?

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

JTable - How to add objects to a table?

javajtable

提问by sam

I have a class

我有一堂课

class Person {
 String name;
 int age;
 Date DOB;
}
Person p1 = new Person(...);
Person p2 = new Person(...);

How do I add objects (like p1, p2) of this class to a table ?

如何将此类的对象(如 p1、p2)添加到表中?

回答by mort

This could be a good start:

这可能是一个好的开始:

http://download.oracle.com/javase/tutorial/uiswing/components/table.html

http://download.oracle.com/javase/tutorial/uiswing/components/table.html

Basically, you will have to create a TableModel, there you can add a method addPerson(Person p)which then takes the data from pand fills it into the table columns.

基本上,您必须创建一个 TableModel,在那里您可以添加一个方法addPerson(Person p),然后从中获取数据p并将其填充到表列中。

回答by camickr

The DefaultTableModel stores data for individual cells. If you want to store data for rows of custom Objects then you need to create a custom TableModel. The Row Table Modelwas designed to replace the DefaultTableModel so that you can work with Objects at a row level. All you need to do is implement the getValueAt() and setValueAt() methods.

DefaultTableModel 存储单个单元格的数据。如果要存储自定义对象行的数据,则需要创建自定义 TableModel。该行表型号设计用于替换的DefaultTableModel,这样就可以在一个行级使用对象。您需要做的就是实现 getValueAt() 和 setValueAt() 方法。

The Bean Table Modelwill handle this for you assuming you have getter/setters for your data fields. Or you you can look at the JButtonTableModelcode example to see how this can be done manually.

豆表型号将帮助您处理该假设你有你的数据字段的getter / setter方法。或者您可以查看JButtonTableModel代码示例以了解如何手动完成此操作。