Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Change color of cell in Jtable

807605Oct 13 2007 — edited Oct 14 2007
I'm trying to change the color of specific cells in jtable. Let me give you an example, lets say cell 1,0 of the jtable I have the word "test". I would color that cell yellow, plus the 3 cells below it, however the cells below it will be empty (no text in the cell, it's just colored). I'm able to do this, but my problem comes in when I add text to another cell. Lets say at cell location 2,2 I have the word "test2" with the cell background color green. I want to do the same thing as before where the 3 cells below it (which are empty) are colored with green. What happens when I add the second cell with with 3 green below it it changes the color of the first cell (just the empty ones below the word test, the cell with the word test stays yellow) to green when I want it to stay yellow.

I assume that it's because the cell is empty, so I need to find a way to set the color of an empty cell and make it stay. Can I do it by cell location? I've already setup my default table cell renderer. Any help or ideas. I hope this make sense. Below is a clip of my default table cell renderer class.

public class CellRenderer extends DefaultTableCellRenderer 
{

    private JLabel comp;
    public Component cell;
    public Color cellColor,cellColor1;
    public void setBorder(Object v)
{       
}
    Color CellRenderer(Color cellColor1){
      this.cellColor=cellColor;
      return cellColor; 
    }
    
    public Component getTableCellRendererComponent
       (JTable table, Object value, boolean isSelected,
       boolean hasFocus, int row, int column) 
    {

           cell = super.getTableCellRendererComponent
           (table, value, isSelected, hasFocus, row, column);
            table.setIntercellSpacing(new Dimension(0,0));
            table.setBorder(BorderFactory.createLineBorder(Color.white));
            setOpaque(true);
            cell.setBackground(Color.white);
            
           if(value instanceof String){              
                String temp = value.toString();
                if(temp.equals("test") || temp.equals("")){
                   cell.setBackground(Color.yellow); 
                }

                if(temp.equals("test2") || temp.equals("")){
                   cell.setBackground(Color.Green); 
                }
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 11 2007
Added on Oct 13 2007
2 comments
676 views