0

I have a JTable with a model created like this :

DefaultTableModel model = new DefaultTableModel(new Object[][] {},new String[] {"Col1", "Col2", "Col3", "Col4", "Col5", "Col6", "Col7", "Col8"}) {
@Override
public Class<?> getColumnClass(int column) {
switch (column) {
case 0: return ImageIcon.class;
case 7: return JButton.class;
default: return String.class;
}
}
};
table = new JTable(model);

But when I use the addRow method, My ImageIcon appears properly but not the JButton. In fact, I get something like javax.Swing.JButt... instead of the JButton!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Simo03
  • 273
  • 3
  • 10
  • 21

2 Answers2

2

When you are adding a new row, it is being populated correctly. (You can see the ImageIcon). So, the JButton object is also being inserted correctly.

The only difference here, JTable does not know how to display it or handle events on it.

That is why JTable calls toString() method on JButton and displays the text (as you mentioned).

javax.swing.JButt......


To overcome this problem, we need to supply two additional objects to the JTable.

  1. TableCellEditor to handle events.
  2. TableCellRenderer to handle painting.

You can find additional information about implementation details here : How to use custom JTable cell editor and cell renderer

Hope this helps.
Good luck.


Edit in response to the comment.

table.getColumnModel().getColumn(7).setCellRenderer(new MyCellRenderer());
// Put painting logic in MyCellRenderer class.

This way you can assign different renderer objects to different columns.

Community
  • 1
  • 1
Tanmay Patil
  • 6,882
  • 2
  • 25
  • 45
  • OK, I understand the problem now. But I want to know how to make the JTable know that in a specific column I want JButton objets? – Simo03 May 09 '14 at 12:14
1

The problem is that JTable doesn’t support a button renderer or editor. You can overcome it using a custom cell editor, ButtonColumn : http://tips4java.wordpress.com/2009/07/12/table-button-column/