Simo03
Simo03

Reputation: 273

Add a JButton to a JTable cell

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!

Upvotes: 0

Views: 648

Answers (2)

Tanmay Patil
Tanmay Patil

Reputation: 7057

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.

Upvotes: 2

user508434
user508434

Reputation:

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/

Upvotes: 1

Related Questions