user3294496
user3294496

Reputation: 1

Changing colour of specific cell in a JTable

I'm trying to change the colour of one or more particular cells in a column in my JTable. The answers I have seen on here all refer to this particular method;

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
    Component y = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    y.setBackground(new Color(255,0,0));

    return y;
}

But the problem is I do not understand in any way how this works, in my other class I have a Jtable of strings and I want to change the colour of certain cells according to their string value, however the solutions i find only allow me to change the colour of an entire column of cells in the jtable and not a specific one.

Upvotes: 0

Views: 927

Answers (2)

ravibagul91
ravibagul91

Reputation: 20755

You can use DefaultTableCellRenderer to color alternate row from JTable.

table.setDefaultRenderer(Object.class, new TableCellRenderer(){
    private DefaultTableCellRenderer DEFAULT_RENDERER =  new DefaultTableCellRenderer();

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if(isSelected){
                    c.setBackground(Color.YELLOW);
                }else{
                if (row%2 == 0){
                    c.setBackground(Color.WHITE);

                }
                else {
                    c.setBackground(Color.LIGHT_GRAY);
                }     }

       //Add below code here
                return c;
            }

        });

If you want to color your row using the value of a particular row then you can use something like this. Add these line to above

if(table.getColumnModel().getColumn(column).getIdentifier().equals("Status")){//Here `Status` is column name
    if(value.toString().equals("OK")){//Here `OK` is the value of row

        c.setBackground(Color.GREEN);
    }   
}

Upvotes: 0

camickr
camickr

Reputation: 324098

I have a Jtable of strings and I want to change the colour of certain cells according to their string value

The same renderer is used for all cells so you need to reset the background every time.

You will need an if condition in your custom renderer code. Something like:

if (!isSelected)
    if (value.equals(...))
        y.setBackground(new Color(255,0,0));
    else
        y.setBackground(table.getBackground())

Upvotes: 5

Related Questions