It's not a secret anymore!
The moose likes Swing / AWT / SWT and the fly likes JTable, custom renderers 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, custom renderers" Watch "JTable, custom renderers" New topic

JTable, custom renderers

Raf Szczypiorski
Ranch Hand

Joined: Aug 21, 2008
Posts: 383
I am using a JTable, but I want to use custom renderers. Actually, I would like to reuse the default renderers, with only one property changed - when the cell is not editable, I want it to be disabled.
The scenario is this - I have a row that contains a few cells, first of which is a combo with a set of values (enum). I am using a custom editor that uses a combo box. When a certain value is chosen, some of the cells in the row should be made "irrelevant", and I want to convey this to the user making the cells uneditable and have them rendered as "disabled". Some of the columns are boolean, whcih the default rederers show as check boxes.
What I did is that I add a TableModelListener to the model, and detect the value set in the column with enums, and if the certain value is set, I add the row to a set of "uneditable" rows (actually, now the whole rows are uneditable, just a few columns), and call fireRowsUpdated for the row. This forces the JTable to redraw the row, asking JTable isCellEditable. In this method, I check if the row is found in the uneditable set, and if it is, I check if the column number asked is to be uneditable. All of this workes fine.
However, I have a question to the renderers. JTable contains static inner classes like BooleanRenderer or NumberRenderer. I would like to reuse these, as the only thing I am changing there is that that in the getTableCellRendererComponent I check with the JTable passed as an argument if a given cell is editable, and if not, I set setEditable(true) or (false) accordingly. Unfortunately, the classes are package private, so I cannot extend them. What I did is pretty much copied the code (border settings, opacity settings and so on) to my own classes, but this doesn't sound like good code reuse, does it?
Is it possible to somehow reuse the default renderers, is there any way I can get hang of them, maybe use composition, and just add my tiny little bit of code? Or is the fact that the classes are package private the end of my dreams, and copying the code to my classes the only thing I can do?

Best refards,
Rob Camick
Ranch Hand

Joined: Jun 13, 2009
Posts: 2451
You might be able to override the preparedRenderer(...) method of JTable to simply set the renderer component to disabled based on the rows in your uneditable Set.
Raf Szczypiorski
Ranch Hand

Joined: Aug 21, 2008
Posts: 383
This is just what I am looking for, this is great. Thank you very much sir!
I agree. Here's the link:
subject: JTable, custom renderers
jQuery in Action, 3rd edition