File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes JTable colored row Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTable colored row" Watch "JTable colored row" New topic

JTable colored row

Juergen Sprindt

Joined: Mar 15, 2002
Posts: 1
Hi Folks!
Does anybody know how to color rows?
I retrieved records from a database into a JTable, but it would be great if special rows could be painted in different colors.
How can I do that?
Thanks in advance...
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Juergen,
In order to do that you'll have to install a custom TableCellRender. The way I would proceed (you may come up with a better way) is create a class, let's call it ColorDBCell which extends JPanel or maybe JTextField. This class will now hold the text representation of each db field. Next I create a ColorDBCellRender which must implement TableCellRenderer which contains one method:

Now inside of this method, you set the background color to whatever you want for our ColorDBCell and there you have it. Remember to typecast the Object value back to ColorDBCell like this:

Finally you need to register the renderer with the JTable similar to this:

This tells the JTable to use our custom renderer for all instances of ColorDBCell.
Hope this helps
Michael Morris

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
I agree. Here's the link:
subject: JTable colored row
It's not a secret anymore!