一种方法是不更改内容,而是提供适当的渲染器,该渲染器在绘制期间检查它是否在弹出窗口内。
概念验证代码片段如下所示:
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;
}
});
注意:上面的例子没有正确处理所有方面(例如焦点边框......),但只是提示您如何进一步进行。