1

I'm new to java. What i am trying to do is to create a table that shows a list of objects. What i want is to give color for specific rows in the JTable based upon the value of the member of an object. I saw a lot of option like using "TableCellRender" and all.I have tried them too. But the problem is that am using the Netbeans IDE so that i am not creating the table by code. Can some one please help me to change row color where the table is defined by the NetBeans??

Thanks in advance.

arvonline
  • 13
  • 1
  • 4

1 Answers1

3

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);
    }   
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59