带有 ImageIcon 列的 Java JTable TableCellRenderer
我有一个带有自定义表格模型的表格,其中有两列。第 0 列是 ImageIcon 类,第 1 列是 String 类。
public Class<?> getColumnClass(int col) {
if (col == 0) {
return ImageIcon.class;
} else {
return String.class;
}
}
当我定义要添加到列中的新 TableCellRenderer 类以便可以设置单元格样式时,它会覆盖 ImageIcon 类并将其设置为字符串。
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;
}
}
关于如何解决这个问题有什么想法吗?
我的错误,它有点隐藏:
当我定义要添加到列中的新 TableCellRenderer 类以便设置单元格样式时,它会覆盖 ImageIcon 类并将其设置为字符串。
所以问题是,当我定义这个 TableCellRenderer 类来设置表格样式时,表格中的 ImageIcon 列会变成“File:...”之类的字符串,而不是实际的图标。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需创建自定义渲染器。 JTable allready 支持包含图标的列的默认渲染器。您需要做的就是重写 getColumnClass() 方法,您似乎正在这样做。
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: