user1861088
user1861088

Reputation: 1733

Let JComboBox change displayed item upon item selection

When I expand the combobox list I should see items such as "one" "two" "three", but when I select, say, "one" and collapse the combobox, I would like to see "1" on display instead of "one".

I have tried adding a ListDataListener to the combobox and inside contentsChanged() I do box.getEditor().setItem(my_map.get("one")) where my_map stores the mappings from "one" to "1" etc.

However, it does not work and I don't know why.. Does something happen after contentsChanged() is called that overwrites my changes?

Any ideas?

Upvotes: 0

Views: 1084

Answers (1)

Howard
Howard

Reputation: 39217

One way would be to not change the content but provide an appropriate renderer which checks during painting if it is inside the popup.

enter image description here

A proof-of-concept code snippet looks as follows:

JComboBox box = new JComboBox(new String[] { "One|1", "Two|2", "Three|3" });

box.setRenderer(new ListCellRenderer<String>() {

    private JList<? extends String> list;
    private final JLabel label = new JLabel() {
        @Override
        public void paintComponent(Graphics g) {
            // Check if parent's parent is the combobox or the dropdown
            int part = getParent().getParent() == list ? 0 : 1;
            label.setText(label.getText().split("\\|")[part]);
            super.paintComponent(g);
        }
    };

    @Override
    public Component getListCellRendererComponent(JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus) {
        this.list = list;
        label.setText(value);
        label.setOpaque(true);
        if (isSelected) {
            label.setForeground(list.getSelectionForeground());
            label.setBackground(list.getSelectionBackground());
        } else {
            label.setForeground(list.getForeground());
            label.setBackground(list.getBackground());
        }
        return label;
    }
});

Note: The example above does not handle all aspects correctly (e.g. focus border ...) but is just a hint how you may proceed further.

Upvotes: 2

Related Questions