Odette Savage
Odette Savage

Reputation: 17

Change row Background in JTable Java

I have a table in my project called tasktable. It retrives data from database (oracle). How can I change the color of the row that has the color in the cell ex. (i,8) automatically when I click the refresh button?

I have tried so many times to put that source code on specific row, but it ended up coloring all the table:

          int count;      
          count = tasktable.getRowCount();
         for (int i=0;i<count;i++)
            { 
                  rr = new Object ();
                   rr = tasktable.getModel().getValueAt(i,8);
                   if(rr.equals("GREEN"))
                   {
                 setBackground(Color.GREEN);
                   }
                    if(rr.equals("red"))
                   {
                       setBackground(Color.red);
                   }
                     if(rr.equals("BLUE"))
                   {
                      setBackground(Color.BLUE);
                   }
                      if(rr.equals("yellow"))
                   {
                     setBackground(Color.yellow);
                   }
                       if(rr.equals("pink"))
                   {
                     setBackground(Color.pink);
                   }
                       if(rr.equals(null))
                   {
                     setBackground(null);
                   }

how can help me out upon this problem ?

Upvotes: 0

Views: 5247

Answers (4)

BenCole
BenCole

Reputation: 2112

If all you're doing is changing row color, subclass your JTable and override the prepareRenderer method:

public Component prepareRenderer(TableCellRenderer renderer,
                             int row,
                             int column) {    
     Component c = super.prepareRenderer(renderer, row, column);
     if (row == HIGHLIGHT_ROW) {
          c.setBackground(BG_COLOR); 
     }
     return c;
}

Upvotes: 1

Sully
Sully

Reputation: 14943

 Component comp = super.getTableCellRendererComponent(
                  table,  value, isSelected, hasFocus, row, col);

 String s =  table.getModel().getValueAt(row, VALIDATION_COLUMN ).toString();
 comp.setForeground(Color.red);

http://www.java-forums.org/awt-swing/541-how-change-color-jtable-row-having-particular-value.html

Upvotes: 0

Dan O
Dan O

Reputation: 6090

setBackground() sets the background color of the JTable, not the background color of each row or cell. You need a TableCellRenderer, as @Recursed said.

Upvotes: 1

Rob Wagner
Rob Wagner

Reputation: 4421

Add a custom TableCellRenderer to your table.

Upvotes: 2

Related Questions