Ok, so I've got a table setup in which I've added a JComboBox to a specific cell as they've done in the example here, but for some reason the combo box won't display until that cell has been selected. If I select that cell, the combo box opens it's list for me to select from. Whether I change the selection or not, if I click to another cell in the table, it then displays the text of the item selected from the combo box as if it was a simple string displayed in the table as desired.
My question is: How do I get it to display the selected value in the JComboBox without having to select the cell first?
edit: One thing I forgot the mention is; rather than declaring the DefaultTableModel data
before-hand like they have, items are instead added to the DTM later using model.addRow();
You can either try creating your own Renderer as in this example.
public void example(){
TableColumn tmpColum =table.getColumnModel().getColumn(1);
String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
JComboBox comboBox = new JComboBox(DATA);
DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
tmpColum.setCellEditor(defaultCellEditor);
tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
table.repaint();
}
/**
Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
JComboBox combo;
public CheckBoxCellRenderer(JComboBox comboBox) {
this.combo = new JComboBox();
for (int i=0; i<comboBox.getItemCount(); i++){
combo.addItem(comboBox.getItemAt(i));
}
}
public Component getTableCellRendererComponent(JTable jtable,
Object value,
boolean isSelected,
boolean hasFocus,
int row, int column) {
combo.setSelectedItem(value);
return combo;
}
}
or you can customize the default Renderer like in this example.
final JComboBox combo = new JComboBox(items);
TableColumn col = table.getColumnModel().getColumn(ITEM_COL);
col.setCellRenderer(new DefaultTableCellRenderer(){
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
label.setIcon(UIManager.getIcon("Table.descendingSortIcon"));
return label;
}
});
The first example makes the cell look like the JComboBox after its clicked. The second example adds an arrow icon to the JComboCox that showcases that the JComboBox is clickable. I used the second example, result can be seen here.
This is the normal behaviour. A table uses renderers and editors. The default renderer for a cell is just a JLabel so all you see is the text. When you click on the cell the editor is invoked so you see the combo box.
If you want the cell to look like a combo box even when it is not being edited then you need to create a combo box renderer for that column.
Read the section from the Swing tutorial on Using Custom Renderers for more information.