1

Being that what gets displayed in the JTable is the stored object's toString, is it somehow possible to display other information?

For example, if I have a simple user object like this:

User

class User {
  private String firstname; 
  private String lastname;
  ... 
}

Can I display the first and last name properties in their own column in a JTable?

Like this:

enter image description here

Currently, I'm storing the string properties of the User object in the JTable rather than the User object itself.

e.g.

// where first/lastname are the strings retrieved 
// via getFirstname() and getLastname() on the User object. 
model.addRow(new Object[] {first, last });

However, the problem with this is all the book keeping involved anytime I need to retrieve and build the Object that the user clicks on in the JTable. Is it possible to store the User object in the JTable, but have it display different properties depending on the column it's in?

1
  • 1
    is the stored object's toString, - please why Commented Nov 29, 2013 at 18:50

1 Answer 1

2

Yes it is. Just define a different TableCellRenderer to each column:

User user = new User("Zack", "Yoshyaro");

DefaultTableModel model = new DefaultTableModel(new Object[]{"First", "Last"}, 0);
model.addRow(new Object[]{user, user});  // note user must be added for each column, but it's the same object
JTable table = new JTable(model);

TableColumn firstName = table.getColumn("First");
firstName.setCellRenderer(...); // a cell renderer that shows user.getFirstName();

TableColumn lastName = table.getColumn("Last");
lastName.setCellRenderer(...); // a cell renderer that shows user.getLastName();

See Using custom Renderer section in How to Use Tables tutorial.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.