JComboBox 项目更改
我的 JComboBox
模型包含诸如 item1
、item2
、item1
之类的项目。我的问题是,当我在 JComboBox
中选择第三个项目 (item1
) 并检查 getSelectedIndex()
时,它总是返回 0。
如果该项目与我的模型如何以不同的方式获得每个项目的索引?例如:
- item1 返回 0
- item 2 返回 1
- item1 返回 2
My JComboBox
model contains item like item1
, item2
, item1
. My problem is when I select third item (item1
) in JComboBox
and check getSelectedIndex()
it always returns 0.
If the item is same in my model how can I get index of each item differently? Like:
- item1 returns 0
- item 2 returns 1
- item1 returns 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它返回 index = 0。因为
getSelectedIndex()
方法对 JComboBox 中的对象使用.equals
并将其与选定的对象进行比较。在您的情况下,因为 item1 也在索引 0 处,所以它发现条件为 true 并返回 0。如果您想获得不同的索引,则必须重写getSelectedIndex()
方法。JComboBox 默认
getSelectedIndex()
方法的概述位于 Java2s:您应该在 2 个条目中获得不同的内容 [如果项目对象有名称或其他任何内容,则可能是 itemName]期望的结果。重写 getSelectedIndex() 并比较所有不同的内容。如果两个条目完全相同,那么添加两次有什么意义呢?
It returns index = 0. Because the method
getSelectedIndex()
use.equals
on objects that are in the JComboBox and compare it with the selected one. In your case because item1 is also at index 0 it finds the condition true and returns 0. If you want to get different index then you have to override thegetSelectedIndex()
method.An outline of default
getSelectedIndex()
method of JComboBox found at Java2s:You should have something [may be itemName if item object has a name or anything else] different in 2 entries to get desired result. Override
getSelectedIndex()
and compare the thing that is meant to be differ in all. If both entries are completely same then whats the point of adding it twice?如果 JComboBox 中的两个条目对应于同一对象,那么即使您单击项目 3,所选的实际项目也将是该对象的第一个条目(即索引最低的条目)
我认为这不适用于相同的对象。
If two entries in the JComboBox correspond to the same Object, then even if you click item 3 the actual item that is selected will be the first entry of that object (i.e. the one with the lowest index)
I don't think that this will work for the same objects.
JList
对于相同的项目没有问题。A
JList
has no problems with identical items.