3

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);
}
  • *"make it always visible and user-friendly?"* - To me, that's a contradiction in terms, if every cell in the column was showing the same popup ALL the time, how would you be able to see the value of the cells below them?? – MadProgrammer Jun 09 '15 at 23:22
  • The dropdown options won't be visible all the time, the problem is that when in a JTable, a ComboBox seems like a regular cell, you only figure out that it's a ComboBox when you click it. – Guilherme Soares Jun 09 '15 at 23:24
  • 2
    And? You could create your own `TableCellRenderer` to make it "look" different if that's important to you (personally, I'd only add a "down arrow" to provide an indication of "more", but that's me) – MadProgrammer Jun 09 '15 at 23:26
  • Possible [duplicate](http://stackoverflow.com/q/17342917/230513). – trashgod Jun 10 '15 at 01:54
  • Only really a duplicate if the accepted proposal is what is used. The user doesn't know in this context, so options are varied. That said, I recommend MadProgrammer's advice. – Gorbles Jun 10 '15 at 11:18

1 Answers1

0

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;
    }
});
CA2C7B
  • 368
  • 1
  • 14