Reputation: 301
I have created a JComboBox and I am using it on a column of a JTable - see code below.
Object[] items = {"1", "2", "3", "4"};
JComboBox comboBox = new JComboBox(items);
comboBox.setRenderer(new customComboBoxRenderer());
myTable.getColumnModel().getColumn(Table.CONF_COL).setCellEditor(new DefaultCellEditor(comboBox));
Now, my problem is that I cannot find a way to make each combo box in the column of the table with the combo boxes to have an initial value (might be different on each combo box) which will also be the selected item of the particular combo box when the program starts. I think the problem is being created because the JTable is using only one JComboBox instance for all the cells of the column and therefore I can never get a different instance of combo box for each of the cells on the column and set the selected item to them.
Any help would be really appreciated.
Many thanks,
Soc
Upvotes: 0
Views: 1977
Reputation: 1
In your customComboBoxRenderer
call setSelectedItem(same type as your jcombobox elements, in this case String)
inside your
getTableCellRendererComponent(.. )
method
Upvotes: 0
Reputation: 109813
read Oracle tutorial How to use Tables - Using a Combo Box as an Editor for working code example
everything depends of value stored in DefaultComboBoxModel
, in your case I'd be store Integer
not String
value for JComboBox
es model
value stored in XxxTableModel
representing selected or inital value in JComboBox
as TableCellEditor
,
there you can store Integer value too, to avoiding any parsing between String and Integer
simple use (JTable
or XxxTableModel
).setValueAt
to display desired value in JTable
(painted by TableCellRenderer
)
more info about TableCellRenderer
and TableCellEditor
in Oracle tutorial
Upvotes: 2