aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Cell renderer for different JComboBox's in same column? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Cell renderer for different JComboBox Watch "Cell renderer for different JComboBox New topic
Author

Cell renderer for different JComboBox's in same column?

Marcus Hathaway
Ranch Hand

Joined: Jun 07, 2005
Posts: 89
Hello everybody,

My problem is that i want to have JComboBoxs in a column in my table. However, the items in the JComboBox are different, and are set depending on other row data.

Using this article (http://www.javaworld.com/javaworld/javatips/jw-javatip102.html) i've almost managed to achieve what i want to do.

In that article on adding multiple JTable cell editors per column, the author is able to decide on the items's for his combo box before he needs to display the table. I can't quite do this in my circumstance. After the data for the table is generated in the form of an Object [][], the table is refreshed like so:



This happens in a refreshTable() method i have created. I also make a call to this method after the table model has been set:



From the above code you may see that the JComboBox data in Object[][] comes in the form of already populated DefaultCellEditor's. This potentially could be populated JComboBox's or simply a Object[] of items. I'm using here DefaulCellEditor's here because it makes sense when calling addEditorForRow.

Ok, so all this works fine and as expected, i can click on an individual cell and get the different combo box values. However, this only happens after the individual cell has been clicked. If the cell is not clicked then the cell initially displays the toString value of the DefaulCellEditor. I can understand why it does this, as this is the value the original table model finds in the object[][].

I've played and tried but without success to try and combat this problem. Is there some way i could maybe use some kind of renderer instead of the setCellEditors method that would display this data correct from the first time of asking?

Any comments or advice on how to go about this would be most appreciated.
Thanks!
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
You have the answer in your post. You should use a CellRenderer for the cells with JComboBox CellEditors.

For example:



This method implements the getTableCellRendererComponent from TableCellRenderer. When the column is has a JComboBox CellEditor it returns the value of the JComboBox selected item. When the column has a CheckBox cellEditor it returns the CheckBox and otherwise it returns what a DefaultCellRenderer would return (renderer is a DefaultCellRenderer).

Hope it helps.

Happy Coding!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Cell renderer for different JComboBox's in same column?