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 实例中的项


基础教程推荐
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13