How to make the JComboBox dropdown always visible in a JTable

744 views Asked by At

I'm using JComboBox with JTables, but the dropdown menu is only "visible" when it's clicked. How can I change this default behavior and make it always visible and user-friendly?

public void start(){
    TableColumn column = table.getColumnModel().getColumn(0);
    JComboBox comboBox = new JComboBox();
    DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement("a");
    model.addElement("b");
    comboBox.setModel(model);
}
1

There are 1 answers

0
CA2C7B On

As I understand it, you would like the cells to always look like JComboBoxes, and not jLabels.

This can easily be accomplished by adding a TableCellRenderer to your TableColumn. Pasting in the following code should have the desired effect.

column.setCellRenderer(new TableCellRenderer() {
    JComboBox box = new JComboBox();

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        box.removeAllItems();
        box.addItem(value.toString());
        return box;
    }
});