简体   繁体   English

带有ImageIcon列的Java JTable TableCellRenderer

[英]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. 第0列是ImageIcon类,第1列是String类。

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. 当我定义要添加到列的新TableCellRenderer类以便我可以设置单元格样式时,它会覆盖ImageIcon类并将其设置为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. 当我定义要添加到列的新TableCellRenderer类以便我可以设置单元格样式时,它会覆盖ImageIcon类并将其设置为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. 所以问题在于,当我定义这个TableCellRenderer类来设置我的表的样式时,我表中的ImageIcon列转向像“File:...”这样的字符串,而不是实际的图标。

There is no need to create a custom renderer. 无需创建自定义渲染器。 JTable allready supports a default renderer for columns containing an Icon. JTable allready支持包含Icon的列的默认渲染器。 All you need to do is override the getColumnClass() method, which you appear to be doing. 您需要做的就是覆盖您似乎正在执行的getColumnClass()方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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