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?
One way would be to not change the content but provide an appropriate renderer which checks during painting if it is inside the popup.
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 (eg focus border ...) but is just a hint how you may proceed further.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.