简体   繁体   中英

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 ?

This could be a good start:

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.

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 Model was 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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