Java JComboBox 的下拉列表与文本框中的文本不同

4
我想创建一个 jcombobox,具有以下外观和行为:
1)在下拉列表中,每行应为代码编号和项目名称。
2)当用户选择其中一行时,在组合框的文本字段组件中只应显示代码编号,而不是项目名称。 (类似于这样)
我该如何做到这一点?
提前表示感谢。
1个回答

1
这可以用两个步骤来完成:

不是很难:

  1. Your JComboBox items must be an Object for example:

    public class Item {
         private String number;
         private String name;
         // Constructor + Setters and Getters
     }
    
  2. A ListCellRenderer which customize how to render the values in the popup list or in the text-field of 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());
            }
        });
    

祝你好运。


谢谢,这几乎是我想要的,但问题是当鼠标悬停在下拉列表上时,其中的项目也会改变。我希望渲染器只能改变文本字段组件中的项目,而不是下拉列表中的项目。 - giorgosMih
看一下更新。将条件更改为 isSelected && list.getSelectedIndex() != index。我认为这是最接近您需求的东西。毕竟,您可以根据 cellHasFocus 参数设置一些前景和背景颜色,以获得更好的表示。 - STaefi
好的,我没有看到更新。谢谢,现在它可以工作了。 - giorgosMih

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接