Java jcombobox different text in dropdown and other text in textbox

I want to create jcombobox, which will look like this:
1) in the drop-down list, each line should be a code number and an element name.
2) when the user selects one of these lines, only the code number should appear in the component of the text field in the combo box, and not the name element. (Something like this)

How can I do this?

Thanks in advance.

+4
source share
1 answer

This is not so difficult to do using two steps:

  • Your elements JComboBoxmust be objects, for example:

    public class Item {
         private String number;
         private String name;
         // Constructor + Setters and Getters
     }
    
  • A ListCellRenderer, JComboBox:

        JComboBox<Item> jc = new JComboBox<Item>();
        jc.setRenderer(new ListCellRenderer<Item>() {
            @Override
            public Component getListCellRendererComponent(
                    JList<? extends Item> list, Item value, int index, boolean isSelected, boolean cellHasFocus) {
                if(isSelected && list.getSelectedIndex () != index)
                    return new JLabel(value.getNumber());
    
                return new JLabel(value.getNumber() +" "+value.getName());
            }
        });
    

.

+1

All Articles