开发者

Java JTable TableCellRenderer With ImageIcon Column

开发者 https://www.devze.com 2023-01-28 12:12 出处:网络
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.

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;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消