通过重写 DefaultTableCellRenderer 将图标添加到 JTable
我试图通过指定我自己的表格单元格渲染器来将图标添加到特定的 JTable 列,如下所示 (基于本教程的部分):
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;
}
}
上面的代码可以工作,但是:
- 所有单元格都有图标而不是 我想要指定的具体内容 if 语句
- Cell MyTableModel.IMAGE_COLUMN 其中 应该只有一个图标也有 文本。
提前致谢
I'm trying to add an icon to a particular JTable column by specifying my own table cell renderer as 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 cell have the icon instead of
the specific one i want specified in
the if statement - Cell MyTableModel.IMAGE_COLUMN which
should only have an icon also has
text.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
出于更好的性能原因,JTable 为其呈现的每个单元重复使用相同的标签。
这意味着每次更改时都需要设置文本和图标。
字体、背景颜色等也是如此,
应该可以解决问题,
For better performance reasons JTable reuses the same label for each cell it renders.
This means you need to set both text and icon each time you change it.
The same goes for fonts, backgroundcolors and the like
should do the trick,