In Swing is possible to create a JComboBox in a JTable, as seen by this guide from Oracle. They have a lovely picture that shows this in action:
However, what the fail to show is that if you haven't clicked on the cell, the dropdown arrows are not visible and it just looks like a normal text label, as seen below:
You can see that knitting has dropdown arrows because I just clicked on it, but the other ones don't. This is sadly less than ideal because there are no visual cues that the cell can be clicked on to show a list of options. In other words, the "Sport" column looks identical to the "Last Name" column. One of them is a dropdown, the other is not, but they visually look the same unless you happen to click on one of them.
Is there any way that this can be done in Swing?
EDIT: To clarify, what I want is for ALL the cells in the "Sport" column to have arrows indicating a dropdown menu, even if they were not the least one clicked. Basically, I want it to look like a combo box whether I've clicked on it or not.
I'm not sure you understand the distintion between "renderer" and "edit" modes in the JTable
. All the cells in the Sport
column in your example are backed by a combobox, when in edit mode.
What I believe you're trying to do is something like...
Which will clutter the UI (IMHO)
So based on the example from here, I modified the code to change the default cell renderer for the Sport
column
public void setUpSportColumn(JTable table,
TableColumn sportColumn) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement("Snowboarding");
model.addElement("Rowing");
model.addElement("Knitting");
model.addElement("Speed reading");
model.addElement("Pool");
model.addElement("None of the above");
comboBox.setModel(model);
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
model = new DefaultComboBoxModel();
model.addElement("Snowboarding");
model.addElement("Rowing");
model.addElement("Knitting");
model.addElement("Speed reading");
model.addElement("Pool");
model.addElement("None of the above");
//Set up tool tips for the sport cells.
ComboBoxTableCellRenderer renderer
= new ComboBoxTableCellRenderer();
renderer.setModel(model);
sportColumn.setCellRenderer(renderer);
}
And added this...
public class ComboBoxTableCellRenderer extends JComboBox implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setSelectedItem(value);
return this;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With