I want to color each rows of table, by using particular values of database
spcification of mine database is some what like ** id name color 1 pavan red 2 xyz white **
i can give a color to complete table using
table.setBackground(new color(158,145,134); please provide me some solution or hint to approch towards answer, Thanks in advance.
Asked
Active
Viewed 177 times
0

Pavan Gomladu
- 66
- 1
- 8
-
10Why do you say it is hard to apply on JTable? Have you checked [this tutorial](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer)? – assylias Mar 30 '12 at 13:08
-
1JXTable (from the SwingX project) has support for Highlighters, and contains an alternate row highlighter by default, making this requirement almost a one-liner – Robin Mar 30 '12 at 14:22
-
but can we apply it for each row as per db value thanks in advance – Pavan Gomladu Mar 31 '12 at 06:27
1 Answers
4
This isn't hard at all with a JTable! In fact, it's incredibly easy!
See my answer here: Highlight a cell in JTable via custom table model
Reproduced for ease:
...Subclass JTable and override JTable.preparedRenderer(TableCellRenderer renderer, int row, int column)
. If the row
and column
numbers are the same, you can change the background color of the Component
returned as the display (usually a JLabel
);
Here's an example that highlights the row the mouse is over:
@Override
public Component prepareRenderer(final TableCellRenderer renderer, final int row, final int column) {
final Component c = super.prepareRenderer(renderer, row, column);
if (row == this.itsRow) {
c.setBackground(Color.RED);
}
return c;
}
where this.itsRow
is an int field updated by a MouseMotionListener
:
this.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
SubclassedJTable.this.itsRow = SubclassedJTable.this.rowAtPoint(e.getPoint());
SubclassedJTable.this.repaint();
}
public void mouseDragged(MouseEvent e) {/***/}
});
-
sir it is necessary to have row and column numbers are the same, to color each row as per db value rply...thanks – Pavan Gomladu Mar 31 '12 at 06:20