java 通过覆盖 DefaultTableCellRenderer 向 JTable 添加图标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1291948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:58:54  来源:igfitidea点击:

Adding an Icon to JTable by overriding DefaultTableCellRenderer

javaswingjtable

提问by n002213f

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):

我正在尝试通过如下指定我自己的表格单元格渲染器来将图标添加到特定的 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;
    }
}

The above code works but:

上面的代码有效,但是:

  1. All cell have the icon instead of the specific one i want specified in the if statement
  2. Cell MyTableModel.IMAGE_COLUMN which should only have an icon also has text.
  1. 所有单元格都有图标,而不是我想要在 if 语句中指定的特定图标
  2. 单元格 MyTableModel.IMAGE_COLUMN 应该只有一个图标也有文本。

Thanks in advance

提前致谢

回答by Peter

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.

出于更好的性能原因,JTable 为它呈现的每个单元重用相同的标签。这意味着您每次更改时都需要设置文本和图标。

The same goes for fonts, backgroundcolors and the like

字体、背景色等也是如此

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

should do the trick,

应该做的伎俩,