Java Jtable , paint each cell in a different color without creating a different renderer for each cell

478 views Asked by At

I'm making a program that is some kind of a room manager,

Every day there are different clients in each room, sometimes 1 client can take a few rooms at the same day.

I want to color every client in its own color. can I do that without creating a unique cell renderer for each client.

I'm new to J-Tables, and this whole rendering system seems to me not so efficient.

this is a screen shot of my app,

I am using a different renderer for the column headers for weekdays and weekends. also, the cells are J-Buttons and the renderer colors them, but only the same color.

The gray cells are "New" and the orange ones are Occupied by clients, different clients, same color :(

the gray cells are "New" and the orange ones are Occupied by clients, different clients, same color :(

any ideas ?

thanks,

Dave

2

There are 2 answers

0
Pelit Mamani On BEST ANSWER

See example #3 ("render red or green") here: http://www.javapractices.com/topic/TopicAction.do?Id=168

The bottom line is, your Renderer can use a single shared JLabel, setting it with a different color depending on the cell (in the example above they extend DefaultTableCellRenderer which extends JLabel, so effectively the same JLabel is used for all cells. If you don't like inheritance you can just use your own shared JLabel). It works is because the JTable rendering process uses the JLabel as a "reusable stamp" - going over the cells serially, "recording" the look of the cell, and moving on. If your table is (say) 5X3 it doesn't really hold 15 lables, just 15 images.

1
Hovercraft Full Of Eels On
  • Create one single cell renderer class
  • Use the state of the cell to determine its color.
  • If column is 0, then set it to salmon.
  • Otherwise if column is non-0 and value suggests that it's occupied, set it to yellow
  • Otherwise grey.
  • Key: it all depends on the logic you have inside your getTableCellRendererComponent(...) method, and that you use the parameters that are passed into this method correctly.