通过重写DefaultTableCellRenderer将图标添加到JTable [英] Adding an Icon to JTable by overriding DefaultTableCellRenderer

查看:123
本文介绍了通过重写DefaultTableCellRenderer将图标添加到JTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过指定我自己的表格单元格渲染器将图标添加到特定的JTable列,如下所示(基于本教程的部分内容):

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

以上代码有效但是:


  1. 所有单元格都有图标而不是
    我希望在
    中指定的特定单位if语句

  2. Cell MyTableModel.IMAGE_COLUMN哪个
    应该只有一个图标也有
    文本。

谢谢你提前

推荐答案

为了更好的性能原因,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

 if(icon == null){
                    label.setText(status);
                    label.setIcon(null);
            }else{  
                    label.setText("");
                    label.setIcon(icon);
            }

应该这样做,

这篇关于通过重写DefaultTableCellRenderer将图标添加到JTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆