JTable Cell Renderer

后端 未结 3 535
走了就别回头了
走了就别回头了 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:27

    Here is a simple solution, use TableCellRenderer as an inner class.

        myTable.setDefaultRenderer(Object.class, new TableCellRenderer()
        {
            JLabel comp = new JLabel();
            String val;
    
            @Override
            public Component getTableCellRendererComponent(
                                 JTable table, 
                                 Object value, 
                                 boolean isSelected, 
                                 boolean hasFocus, 
                                 int row, 
                                 int column)
            {
                comp.setOpaque(true);
                comp.setForeground(Color.BLACK); // text color
    
                if (value != null)
                {
                    val = value.toString();
                    comp.setText(val);
    
                    if (val.equalsIgnoreCase("red"))
                    {
                        comp.setBackground(Color.RED);
                    }
                    else if (val.equalsIgnoreCase("yellow"))
                    {
                        comp.setBackground(Color.YELLOW);
                    }
                    else if (val.equalsIgnoreCase("green"))
                    {
                        comp.setBackground(Color.GREEN);
                    }
                    else
                    {
                        comp.setBackground(Color.WHITE);
                    }
                }
                return comp;
            }
        });
    

提交回复
热议问题