JTable Cell Renderer

后端 未结 3 534
走了就别回头了
走了就别回头了 2020-12-03 12:08

I\'m following some code I found, (Yes I understand how it works) It\'s from here :Code Link

What i\'m trying to do is set a cells Foreground color if the cells valu

3条回答
  •  情话喂你
    2020-12-03 12:38

    Add this line:

    c.setOpaque(true);
    

    The Component returned by getTableCellRendererComponent must be opaque in order to see changes on background and foreground color. The problem here is also another: you are extending DefaultTableCellRenderer (that is a JComponent) but you are returning a Component that hasn't setOpaque method. I would refactor your code like this:

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,int row,int col) {
    
        String s = table.getModel().getValueAt(row, col).toString();
        this.setOpaque(true);
        if (s.equalsIgnoreCase("yellow")) {
            this.setForeground(Color.YELLOW);
        }
        else {
            this.setBackground(Color.WHITE);
        }
    
        return this;
    }
    

提交回复
热议问题