JComboBox具有相同名称的多个项目

问题描述 投票:1回答:1

我正在使用Eclipse和WindowBuilder。在我的JComboBox中,可以多次显示名称。但是问题是我无法选择名称相同的第二项。它总是选择列表中的第一个。我不能处理第二个。我无法发布图片,所以这里是它的链接:http://oi59.tinypic.com/15rmbcz.jpg

例如,我用于删除列表中名称的代码如下:

for (Element customer : dList) {
    String name = customer.getChildText("name");
    if (GuiMain.item.equals(name)) {
        String birthday = customer.getChildText("birthday")
        if (bDay.equals(birthday)) {
            customer.getParent().removeContent(customer);
            document.setContent(root);

            XMLOutputter xmlOutput = new XMLOutputter();

            xmlOutput.setFormat(Format.getPrettyFormat());
            xmlOutput.output(document, new FileOutputStream("SAVE//File.xml"));
            continue;
        }
    }
}

对此有什么解决方案吗?

java jcombobox windowbuilder
1个回答
1
投票

您发布的代码不足以让我确定JComboBox中的内容以及如何对其进行修改。但是,以下代码可以为您提供帮助:

private static class MyString {

    private static AtomicInteger objectCount = new AtomicInteger(0);

    private final String string;
    private final int id;

    public MyString(String string) {
        this.string = string;
        this.id = objectCount.getAndIncrement();
    }

    @Override
    public String toString() {
        return string;
    }

}

public static void main(String[] args) {
    Vector<MyString> vector = new Vector<>();
    vector.add(new MyString("One"));
    vector.add(new MyString("Two"));
    vector.add(new MyString("Two"));;
    vector.add(new MyString("Three"));

    JComboBox<MyString> box = new JComboBox<>(vector);
    box.addItemListener(e -> {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            MyString item = (MyString) e.getItem();
            System.out.println(String.format("Selected: %s (id=%s)", item, item.id));
        }
    });

    JFrame frame = new JFrame();
    frame.setContentPane(box);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

请注意,MyString不会覆盖equals方法,这意味着如果两个对象是同一实例,则它们是相等的(因此id实际上是多余的,只是打印输出。

© www.soinside.com 2019 - 2024. All rights reserved.