Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

change JTable cell background color dynamically

 
Gerald Tan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..
 
Gerald Tan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Steffen.
I assumed it wouldn't work, but I guess I didn't understand the Cell Renderers very well
Gerald Tan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic