Stephane Grenier
Stephane Grenier

Reputation: 15925

Java 7 Generics on Swing components

I have a class such that it extends a Swing component such as:

public class MyCustomClass extends JComboBox

The problem here is that I get the compiler warning:

JComboBox is a raw type. References to generic type JComboBox should be parameterized

I'm not sure to parameterize the JComboBox so that whatever class further extends from here can use any type of object. I've tried to put it as extends JComboBox, and so on, but that doesn't work. Any suggestions would be appreciated.

Upvotes: 3

Views: 1860

Answers (4)

MadProgrammer
MadProgrammer

Reputation: 347314

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

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)

Upvotes: 4

John3136
John3136

Reputation: 29266

The parameter is the type of object you want in the ComboBox.

Your choices are:

A: MyCustomClass always expects the same type of object, so you do something like:

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. So you do:

public class MyCustomClass<T> extends JComboBox<T>

Upvotes: 3

MByD
MByD

Reputation: 137382

JComboBox became a generic class in Java 7, e.g. you should tell the compiler what type of objects are inside the JComboBox instance. so you can either make you class generic, or specify the type of the JComboBox.

Upvotes: 2

zoli
zoli

Reputation: 468

if there are no restrictions on the type parameter for the JComboBox, then you can go with:

public class MyCustomClass<T> extends JComboBox<T>

If I remember the syntax correctly.

Upvotes: 6

Related Questions