为什么 JComboBox 上的 getSelectedItem() 不是通用的?
Java 7 中的 JCombobox 已更新为使用泛型 - 我一直认为这是一个疏忽,但事实并非如此,所以我很高兴看到这一变化。
然而,当尝试以这种方式使用 JCombobox 时,我意识到我期望使用这些泛型类型的方法 仍然只是返回 Object。
这到底是为什么?对我来说,这似乎是一个愚蠢的设计决定。我意识到底层 ListModel 有一个通用的 < code>getElementAt() 方法,所以我将使用它来代替 - 但这是一种迂回的方式,它看起来可以在 JComboBox 本身上进行更改。
JCombobox in Java 7 has been updated to use generics - I always thought it was a bit of an oversight that it didn't already so I was pleased to see this change.
However, when attempting to use JCombobox in this way, I realised that the methods I expected to use these generic types still just return Object.
Why on earth is this? It seems like a silly design decision to me. I realise the underlying ListModel has a generic getElementAt()
method so I'll use that instead - but it's a bit of a roundabout way of doing something that appears like it could have been changed on JComboBox itself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想您指的是
getSelectedItem()
?原因是,如果组合框是可编辑的,则所选项目不一定包含在支持模型中,并且不受通用类型的限制。例如,如果您有一个模型为 [1, 2, 3] 的可编辑
JComboBox
,您仍然可以在组件中键入“foo”,并且getSelectedItem()
将返回字符串“foo”而不是整数类型的对象。如果组合框不可编辑,您始终可以遵循 cb.getItemAt(cb.getSelectedIndex()) 来实现类型安全。如果未选择任何内容,则将返回
null
,这与getSelectedItem()
的行为相同。I suppose you refer to
getSelectedItem()
?The reason is that if the combo box is editable, the selected item is not necessarily contained in the backing model and not constrained to the generic type. E.g. if you have an editable
JComboBox<Integer>
with the model [1, 2, 3], you can still type "foo" in the component andgetSelectedItem()
will return the String "foo" and not an object of type Integer.If the combo box is not editable, you can always defer to
cb.getItemAt(cb.getSelectedIndex())
to achieve type safety. If nothing is selected this will returnnull
, which is the same behaviour asgetSelectedItem()
.这是一个类型安全的版本:
Here is a type-safe version: