Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable - How to add objects to a table?

Tags:

java

jtable

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 ?

like image 256
sam Avatar asked Sep 01 '11 09:09

sam


People also ask

How do you add an object to a table in Java?

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. ... and fills it into the table columns.

How do I change the appearance of data in a JTable cell?

We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it.

Can I add buttons in JTable?

We can add or insert a JButton to JTable cell by customizing the code either in DefaultTableModel or AbstractTableModel and we can also customize the code by implementing TableCellRenderer interface and need to override getTableCellRendererComponent() method.

How do you make a JTable cell editable?

jTableAssignments = new javax. swing. JTable() { public boolean isCellEditable(int rowIndex, int colIndex) { return editable; }};


2 Answers

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.

like image 192
mort Avatar answered Oct 09 '22 09:10

mort


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.

like image 26
camickr Avatar answered Oct 09 '22 11:10

camickr