简体   繁体   English

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

[英]JTable - How to add objects to a table?

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)添加到表中?

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 p and fills it into the table columns. 基本上,您必须创建一个TableModel,在那里您可以添加一个方法addPerson(Person p) ,然后从p获取数据并将其填入表列。

The DefaultTableModel stores data for individual cells. DefaultTableModel存储单个单元格的数据。 If you want to store data for rows of custom Objects then you need to create a custom TableModel. 如果要存储自定义对象行的数据,则需要创建自定义TableModel。 The Row Table Model was designed to replace the DefaultTableModel so that you can work with Objects at a row level. 行表模型旨在替换DefaultTableModel,以便您可以在行级别处理对象。 All you need to do is implement the getValueAt() and setValueAt() methods. 您需要做的就是实现getValueAt()和setValueAt()方法。

The Bean Table Model will handle this for you assuming you have getter/setters for your data fields. 假设您拥有数据字段的getter / setter, Bean表模型将为您处理此问题。 Or you you can look at the JButtonTableModel code example to see how this can be done manually. 或者您可以查看JButtonTableModel代码示例,了解如何手动完成此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM