简体   繁体   中英

Java JTable TableCellRenderer With ImageIcon Column

I have a table with a custom table model which has two columns. Column 0 is an ImageIcon class, and Column 1 is a String class.

public Class<?> getColumnClass(int col) {
    if (col == 0) {
        return ImageIcon.class;
    } else {
        return String.class;
    }
}

When I define a new TableCellRenderer class to be added to the columns so I can style the cells, it overwrites the ImageIcon class and sets it to a String.

public class CustomTableCellRenderer extends DefaultTableCellRenderer
{
    public Component getTableCellRendererComponent (JTable table, Object obj, boolean isSelected,     boolean hasFocus, int row, int 
    column)
    {
    Component cell = super.getTableCellRendererComponent(table, 
      obj, isSelected, hasFocus, row, column);
    if(isSelected)
     cell.setBackground(Color.BLUE);
    return cell;
    }
}

Any ideas on how to fix this?

My mistake, it is sort of hidden:

When I define a new TableCellRenderer class to be added to the columns so I can style the cells, it overwrites the ImageIcon class and sets it to a String.

So the problem is that, when I define this TableCellRenderer class to style my table, the ImageIcon columns in my table turn to Strings like "File:..." instead of the actual icon.

There is no need to create a custom renderer. JTable allready supports a default renderer for columns containing an Icon. All you need to do is override the getColumnClass() method, which you appear to be doing.

Another possible solution is to just set the icon yourself. I'm not sure if this is the best solution, but it works:

   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column) {
      Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
               column);
      ((JLabel)cell).setIcon((Icon)value);
      ((JLabel)cell).setText("");
      ((JLabel)cell).setHorizontalAlignment(JLabel.CENTER);
      if (isSelected) {
         cell.setBackground(Color.blue);
      } else {
         cell.setBackground(null);
      }
      return cell;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM