dcsimg
JCheckBox and JComboBox in JTable cell
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Tuesday, February 28, 2006 09:09 AM


Hi all! Is it possible for a JCheckBox or JComboBox to appear inside a JTable cell? Or do the cells only contain String type? If it is possible, how will I make it? I have tried but it seems that it only displays the toString method when I used the setValueAt.



Thank you for the answers and fast response!

Re: JCheckBox and JComboBox in JTable cell

Posted By:   Almagest_FUTT  
Posted On:   Tuesday, February 28, 2006 09:30 PM

The javax.swing.table.TableModel a JTable relies on has a method getColumnClass(int column). The Class returned by this method defines which CellRenderers and CellEditors are used.


By default, if this method returns, say, Boolean.class, the JTable will use a JCheckBox to render the value. If the cell is editable too (TableModel#isCellEditable(int, int)), then a JCheckBox is used as an editor, too.


There is no way I know of to render a value in a cell with a JComboBox, I mean not in the legacy classes. It wouldn't make any sense, either way.

However, it is quite easy to make the JTable use a JComboBox as an editor for a particular column.

Say you had constructed a JComboBox with the values you want to be chosen from, then you could write:


JComboBox jcb = ...;
myJTable.setDefaultEditor(MySpecialClass.class, new DefaultCellEditor(jcb));

Then, if the TableModel#getColumnClass(int) would return MySpecialClass.class for a particular column, and if the cell were editable, then the JTable would use the specified JComboBox to let the user edit the value (the result of this process is committed to the model using TableModel#setValueAt(int, int)).


You may (and should) familiarize yourself with the concepts of models, renderers, editors by reading around here.

About | Sitemap | Contact