简体   繁体   English

Swing组件上的Java 7 Generics

[英]Java 7 Generics on Swing components

I have a class such that it extends a Swing component such as: 我有一个类,它扩展了Swing组件,如:

public class MyCustomClass extends JComboBox

The problem here is that I get the compiler warning: 这里的问题是我得到编译器警告:

JComboBox is a raw type. JComboBox是原始类型。 References to generic type JComboBox should be parameterized 应参数化对泛型类型JComboBox的引用

I'm not sure to parameterize the JComboBox so that whatever class further extends from here can use any type of object. 我不确定参数化JComboBox,以便从这里进一步扩展的任何类都可以使用任何类型的对象。 I've tried to put it as extends JComboBox, and so on, but that doesn't work. 我试图把它作为扩展JComboBox,等等,但这不起作用。 Any suggestions would be appreciated. 任何建议,将不胜感激。

if there are no restrictions on the type parameter for the JComboBox, then you can go with: 如果对JComboBox的类型参数没有限制,那么你可以使用:

public class MyCustomClass<T> extends JComboBox<T>

If I remember the syntax correctly. 如果我正确记住了语法。

The generics effect the type of data expected to be in the model. 泛型会影响预期在模型中的数据类型。 This is a neat feature in the long term, but may mean some short term pain. 从长远来看,这是一个很好的功能,但可能意味着一些短期的痛苦。

You have two options that I can think of. 你有两个我能想到的选择。

Firstly, construct you custom class so it allows the generics to fall through... 首先,构建自定义类,以便允许泛型通过......

public class MyCustomClass<E> extends JComboBox<E>

Secondly, pass an Object as the data type for the combo box 其次,传递一个Object作为组合框的数据类型

public class MyCustomClass extends JComboBox<Object>

(or thirdly, constrain the custom combo box to a pre-defined data type for the purpose it was build for) (或者,第三,将自定义组合框约束为预定义的数据类型,以实现其构建目的)

The parameter is the type of object you want in the ComboBox. 该参数是ComboBox中所需的对象类型。

Your choices are: 你的选择是:

A: MyCustomClass always expects the same type of object, so you do something like: 答: MyCustomClass总是期望相同类型的对象,所以你做的事情如下:

public class MyCustomClass extends JComboBox<String>

OR 要么

B: MyCustomClass still isn't "deep enough" down the tree to know the type of class it will work on. B: MyCustomClass在树下仍然“不够深”,无法知道它将使用的类的类型。 So you do: 所以你也是:

public class MyCustomClass<T> extends JComboBox<T>

JComboBox became a generic class in Java 7, eg you should tell the compiler what type of objects are inside the JComboBox instance. JComboBox成为Java 7中的泛型类,例如,您应该告诉编译器JComboBox实例中的对象类型。 so you can either make you class generic, or specify the type of the JComboBox . 所以你可以让你的类通用,或者指定JComboBox的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM