Adding an icon in JTable by overriding DefaultTableCellRenderer

I am trying to add an icon to a specific JTable column by specifying my own rendering of table cells as shown below ( based on parts of this tutorial ):

public class MyTableCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if(column == MyTableModel.IMAGE_COLUMN){ String status = (String)value; Icon icon = StatusImageUtil.getStatusIcon(status); if(icon == null){ label.setText(status); }else{ label.setIcon(icon); } } return label; } } 

The above code works, but:

  • All cells have an icon instead of a specific one, which I want to indicate in the if statement
  • Cell MyTableModel.IMAGE_COLUMN, which should only have a text icon.

Thank you in advance

+3
source share
1 answer

To improve performance, JTable reuses the same label for each cell that it displays. This means that you need to set both the text and the icon every time you change it.

The same goes for fonts, colored backgrounds, etc.

  if(icon == null){ label.setText(status); label.setIcon(null); }else{ label.setText(""); label.setIcon(icon); } 

gotta do the trick

+4
source

All Articles