在对象的JComboBox实例项 [英] Item in JComboBox instance of an object

查看:186
本文介绍了在对象的JComboBox实例项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有以下code,看是否在JComboBox中的项目是一个类(Persoon)的实例。

Hello I have the following code to see if an item in the JComboBox is instance of a class(Persoon).

    public class ItemChangeListener implements ItemListener {

        Persoon selectedPerson;
        RekeningApp app;
        PersoonView view;

        public ItemChangeListener(PersoonView view) {

            this.view = view;

        }

        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                Object item = event.getItem();
                System.out.println("Itemchangelistener " + item);
                // do something with object
                if(item instanceof Persoon) {
                    System.out.println("Instance");
                    this.selectedPerson = (Persoon) item;
                    view.setOverzicht(this.selectedPerson);
                } else {
                    this.selectedPerson = null;
                }
            }
        }

    }

项的输出是persoon.name变量的值。所以在JComboBox中的项目实际上是字符串。

The output of item is the value of persoon.name variable. so the items in the JComboBox are actually strings.

这是JComboBox的列表是如何设置的。

this is how the JComboBox list is set.

personenList.addItem(persoon.getNaam());

我的问题是..我怎么能检查如果这Persoon对象excists,是一样的,在JComboBox中?

My question is.. how can I check If this Persoon object excists and is the same as in the JComboBox?

推荐答案

您应该添加到的JComboBox 对象,不只是名字,所以当你调用对象项目= event.getItem(); 这将返回,而不是字符串。如果你想在 JComboBox中显示这个人的名字,覆盖的toString 方法人类是这样的:

You should add to the JComboBox the Person objects, not just the name, so when you call Object item = event.getItem(); this will return the Person, not an String. If you want to display the person's name in the JComboBox, override the toString method in Person class to something like this:

public String toString()
    return this.naam;
}

和您应添加项目到列表中。

And you should add the items to the list.

personenList.addItem(persoon);   

修改

如果您不希望(或可以)覆盖,你应该使用自定义渲染器的的toString 方法。这是一个链接,例如:

If you don't want (or can) override the toString method you should use a custom renderer. This is a link to and example:

http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer

这篇关于在对象的JComboBox实例项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆