为什么JComboBox不是通用的getSelectedItem()? [英] Why isn't getSelectedItem() on JComboBox generic?

查看:127
本文介绍了为什么JComboBox不是通用的getSelectedItem()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 7中的JCombobox已更新为使用泛型 - 我一直认为这是一种疏忽,它还没有发布,所以我很高兴看到这种变化。



然而,当试图以这种方式使用JCombobox时,我意识到我期望使用这些泛型类型的方法仍然返回 Object。



这究竟是为什么?这对我来说似乎是一个愚蠢的设计决定。我意识到底层的 ListModel 有一个通用的 getElementAt()方法,所以我会用它来代替 - 但它有点像是在JComboBox本身上可能已经改变的那样做了一些迂回的做法。

解决方案

我想你引用 getSelectedItem()



原因是如果组合框是可编辑的,则选择的项目不一定包含在支持模型中,并且不受限于通用类型。例如。如果在模型[1,2,3]中有可编辑的 JComboBox< Integer> ,则仍然可以在组件中键入foo,并在 getSelectedItem()将返回字符串foo而不是Integer类型的对象。



如果组合框不可编辑,您可以总是遵循 cb.getItemAt(cb.getSelectedIndex())来实现类型安全。如果没有选择,这将返回 null ,这与 getSelectedItem()


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.

解决方案

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 and getSelectedItem() 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 return null, which is the same behaviour as getSelectedItem().

这篇关于为什么JComboBox不是通用的getSelectedItem()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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