user3684431
user3684431

Reputation: 27

How to set color of rows dynamically in jtable?

I have been seen many articles but I don't understand how to do it!

I want to change the color of some rows in JTable. The table has 3 columns: a, b and c.

The rules

  1. If the value of a<=b the color of the entire row must be red
  2. If the value of a>=c the color of the entire row must be yellow
  3. in default the color of row must be blue.

Upvotes: 1

Views: 1884

Answers (1)

Tej Kiran
Tej Kiran

Reputation: 2238

Try the following code

public class IconifiedRenderer extends JLabel implements TableCellRenderer {
public IconifiedRenderer() {
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    JLabel label = this;
    int cellValueA=-1;
    int cellValueB=-1;
    int cellValueC=-1;
    try {
        setOpaque(true);
        label.setText(String.valueOf(value));
       try {
            cellValueA = Integer.parseInt(String.valueOf( table.getValueAt(row, 0))); //0th for A
        } catch (ArrayIndexOutOfBoundsException aa) {
            //ignore
            cellValueA=-1;
        }
       try {
            cellValueB = Integer.parseInt(String.valueOf( table.getValueAt(row, 1))); //1th for A
        } catch (ArrayIndexOutOfBoundsException aa) {
            //ignore
            cellValueB=-1;
        }
       try {
            cellValueC = Integer.parseInt(String.valueOf( table.getValueAt(row, 2))); //2th for A
        } catch (ArrayIndexOutOfBoundsException aa) {
            //ignore
            cellValueC=-1;
        }
       label.setBackground(Color.BLUE);

       if(cellValueA<=cellValueB){
           label.setBackground(Color.RED);
       }
       if(cellValueA>=cellValueC){
           label.setBackground(Color.YELLOW);
       }
    } catch (Exception ex) {
        // no need to handle
    }
    return label;
}

Add this render class and set the render on you table column

    jTable1.getColumnModel().getColumn(0).setCellRenderer(new IconifiedRenderer());
    jTable1.getColumnModel().getColumn(1).setCellRenderer(new IconifiedRenderer());
    jTable1.getColumnModel().getColumn(2).setCellRenderer(new IconifiedRenderer());

It will show your table like this...

enter image description here

Upvotes: 1

Related Questions