aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes change JTable cell background color dynamically Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "change JTable cell background color dynamically" Watch "change JTable cell background color dynamically" New topic
Author

change JTable cell background color dynamically

Gerald Tan
Greenhorn

Joined: Jul 17, 2002
Posts: 7
Dear Friends,
Seeking some assistance...
Can I change the background color of a JTable cell dynamically. (ie during runtime).
For example, when I click on a Button,
I want the background color of
cell row 0 column 5 in my dataTable
to turn green.
Am I right to think that this cannot be achieved through a custom
cell renderer?
Many thanks,
Gerald Tan
Steffen Foldager
Ranch Hand

Joined: Mar 22, 2001
Posts: 58
You need a custom TableCellRenderer like this one (taken from a project so it won't work for you, but anyway it's a CellRenderer):

Then you need to associate the CellRenderer with the table like this (constuctor of class MainTable):

Then you need to associate clicks on the header with changes in the TableModel. For all this I recommend this link with lots of examples.
Have fun..


Steffen Foldager<p>Sun Certified Java Programmer<br />Sun Certified Web Component Developer
Gerald Tan
Greenhorn

Joined: Jul 17, 2002
Posts: 7
Thanks Steffen, to your response to my question in JavaRanch regarding setting cell background colors of tables.
However, I need to do them *dynamically*,
that is, for example, when I add an ActionListener
to a button, what should I put in the AcitonListener body so that I could change background color of a particular cell in my JTable.
It appears that the custom Cell Renderer way that you suggested only works when the JTable is loaded for the first time. After the JTable is loaded and shown on the screen, how do I dynamically change the colors of table cells?
Thanks!!
Gerald Tan
Steffen Foldager
Ranch Hand

Joined: Mar 22, 2001
Posts: 58
Hi Gerald
The getTableCellRendererComponent method of the CellRenderer is actually very dynamic. It is called everytime changes happen to the table (being scrolled, selection changes etc.).
Actually, it is being called that often that I have run into performance issues with the above code (see other thread in this forum). Which is why you should subclass DefaultTableCellRenderer instead.
I'm pretty sure that TableCellRenderer is what you are looking for
Steffen
[ July 18, 2002: Message edited by: Steffen Foldager ]
Gerald Tan
Greenhorn

Joined: Jul 17, 2002
Posts: 7
Thanks Steffen.
I assumed it wouldn't work, but I guess I didn't understand the Cell Renderers very well
Gerald Tan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: change JTable cell background color dynamically