Item in JComboBox instance of an object(对象的 JComboBox 实例中的项)
问题描述
您好,我有以下代码来查看 JComboBox 中的项目是否是类(Person)的实例.
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;
}
}
}
}
item 的输出是 person.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 对象是否存在并且与 JComboBox 中的相同?
My question is.. how can I check If this Persoon object excists and is the same as in the JComboBox?
推荐答案
您应该将 Person
对象添加到 JComboBox
中,而不仅仅是名称,所以当您调用Object item = event.getItem();
这将返回 Person
,而不是 String
.如果要在 JComboBox
中显示人名,请将 Person
类中的 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/教程/uiswing/components/combobox.html#renderer
这篇关于对象的 JComboBox 实例中的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对象的 JComboBox 实例中的项
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01