1

I want to color specific cells at the same time from a jtable

For example, the cells with column = 1 and row i+2 (i from 0 to 5 ).

I successfully colored a specific cell using a CustomTableCellRenderer like the example show

public class CustomTableCellRenderer extends DefaultTableCellRenderer 
{  
   int x;
   int y;

    CustomTableCellRenderer(int x,int y){ //constructor

        this.x= x;
        this.y=y;
    }   

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int column) 
    {
        Component cell = super.getTableCellRendererComponent
           (table, value, isSelected, hasFocus, row, column);

        if ( ((row == x) && (column == y))) { //test of equivalence of x and y as parameter
                cell.setBackground(Color.green);
            }

            else {
                cell.setBackground(Color.WHITE);
            }
        return cell;
    }
}
Cheesebaron
  • 24,131
  • 15
  • 66
  • 118
  • 1
    Unnnghghhh code formatting. *twitch* – asteri Sep 24 '13 at 13:18
  • Have you seen [this](http://stackoverflow.com/questions/5821724/changing-color-of-cell-in-jtable?rq=1). Maybe its close to what you need. – kgdesouz Sep 24 '13 at 13:24
  • i can't understand it well i need a working code and thanks – user2811139 Sep 24 '13 at 13:28
  • please what is question, where is problem, for better help sooner post an [SSCCE](http://sscce.org/), short, runnable, compilable with hardcoded valuse for JTable with clear desription about your goal – mKorbel Sep 24 '13 at 16:55

1 Answers1

0
Try this

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

            @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);
                }     }

                return c;
            }

        });
ravibagul91
  • 20,072
  • 5
  • 36
  • 59