Results 1 to 4 of 4
Thread: CustomTableCellRenderer
- 11-07-2011, 08:18 PM #1
Member
- Join Date
- Oct 2011
- Posts
- 90
- Rep Power
- 0
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; } }
- 11-07-2011, 09:14 PM #2
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,609
- Rep Power
- 5
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)
- 11-07-2011, 09:18 PM #3
Senior Member
- Join Date
- Jul 2009
- Posts
- 1,143
- Rep Power
- 5
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() );
- 11-07-2011, 10:00 PM #4
Member
- Join Date
- Oct 2011
- Posts
- 90
- Rep Power
- 0


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks