Search code examples
javacolorsrowcell

change jtable row color


I use this code on jtable customize code in custom creation but my selected row not changed please help me for soft this problem

    jtablexml = new javax.swing.JTable(){
public Component prepareRenderer ( TableCellRenderer renderer, int row, int column ){
    Component component = super.prepareRenderer(renderer,row,column);
    Object value = getModel().getValueAt(row,column);
    if(value.equals(null)){
        component.setBackground(Color.RED);
        component.setForeground(Color.BLACK);        }
    else{
        component.setBackground(Color.WHITE);
        component.setForeground(Color.BLACK);        }
        jtablexml.setSelectionBackground(Color.GREEN);
    return component;    }

};


Solution

  • but my selected row not changed

    Your logic overrides the default selection of the row.

    You need an additional check to make sure the row is not highlighted by default:

    Component component = super.prepareRenderer(renderer,row,column);
    
    if (!isRowSelected(row))
    {
        // add custom highlighting here
    }
    
    return component; 
    

    See Table Row Rendering for other row rendering examples.

    Also, don't try to change a property of the table in the renderer.