Results 1 to 4 of 4
  1. #1
    joeyvitoro is offline Member
    Join Date
    Oct 2011
    Posts
    90
    Rep Power
    0

    Default CustomTableCellRenderer

    Hello, I'm trying to change the background color of a JTable cell based on what's in it. Specifically, if the cell is different than the cell above it I want it to be red. My code below compiles, but everything after the first change is red. So if I have a row that reads {1, 1, 1, 2, 2, 2}, I would expect that the first 2 be red, but instead all 2's are red. Thanks in advance

    Java Code:
    class CustomTableCellRenderer extends DefaultTableCellRenderer {	
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) 
    	{
    		Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    		if(row>0 && (!(table.getModel().getValueAt(row, column).equals(table.getModel().getValueAt(row-1, column)))))
    		{
    		c.setBackground(Color.RED);
    		}
    		return c;
    }
    }

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    6

    Default Re: CustomTableCellRenderer

    See the tutorial on renderers - specify an else to set the background when the condition is not met.
    How to Use Tables (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)

  3. #3
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,226
    Rep Power
    6

    Default Re: CustomTableCellRenderer

    ... and don't forget to check if the row is selected:
    Java Code:
    if (!isSelected)
        if (redCellCondition)
            c.setBackground( Color.RED );
        else
            c.setBackground( table.getBackground() );

  4. #4
    joeyvitoro is offline Member
    Join Date
    Oct 2011
    Posts
    90
    Rep Power
    0

    Default Re: CustomTableCellRenderer

    Works...Thanks to both of you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •