Reputation: 15925
I have a Utils class such that:
public static void setComboBoxDefaultWidth(JComboBox cb)
{
cb.setPrototypeDisplayValue("mmmmmmmmmmmmmmmmmmmmmmmmmm");
}
The problem is that this results in a compiler warning:
JComboBox is a raw type. References to generic type JComboBox should be parameterized
I'm not sure how to parameterize the generic so that the calling method and the function both work (no compiler errors). I can resolve one but not both for whatever reason...
Upvotes: 3
Views: 454
Reputation: 15925
You can't if you want to keep the JComboBox for any type of Generic.
Upvotes: 0
Reputation: 63104
If your JComboBox
s always contains String, the syntax would be:
public static void setComboBoxDefaultWidth(JComboBox<String> cb)
{
cb.setPrototypeDisplayValue("mmmmmmmmmmmmmmmmmmmmmmmmmm");
}
Upvotes: 1
Reputation: 133609
The fact is that JComboBox
wasn't generic in Java6 but it became generic with 7 just because the design was flawed (since getItemAt()
returned an Object type you had to manually cast it).
The method is declared as
public void setPrototypeDisplayValue(E prototypeDisplayValue)
This means that, you must have a specific instance of a specific class to call it, and the type must correspond to the one declared for your combo box:
public void setComboBoxDefaultWidth(JComboBox<String> cb) {
cb.setPrototypeDisplayValue("mmmmmmmmmmmmmmmmmmmmmmmmmm");
}
You are forced to do it because you are passing a String
to the method so the JComboBox
must contain String
s.
The above solution is what you need to do when the method that you want to invoke requires a parameter of the generics type. Otherwise you couldn't specify it (without narrwing how many the target) and you would have to use the wildcard ?
exists: if a method doesn't care about what is the specific type of the generic class you just need to specify that the JComboBox
has a generic type without worrying about what the type is:
public static void setComboBoxDefaultWidth(JComboBox<?> cb) {
cb.setLightWeightPopupEnabled(true);
}
The syntax <?>
just literally means unknown type, the parameter is indeed a JComboBox
of unknown type items.
Upvotes: 4
Reputation: 47607
The prototype display value must of the same type as the one typing your JComboBox.
Given a JComboBox<E>
, you can invoke the method setPrototypeDisplayValue(E prototypeDisplayValue)
only if you know the type. Therefore, using a wildcard (?) is not an option. Currently, all you can do is to have:
public static void setComboBoxDefaultWidth(JComboBox<String> cb) {
cb.setPrototypeDisplayValue("mmmmmmmmmmmmmmmmmmmmmmmmmm");
}
Another option you could have would be this:
public static <E> void setComboBoxDefaultWidth(JComboBox<E> cb, E prototypeValue) {
cb.setPrototypeDisplayValue(prototypeValue);
}
but it is pointless.
Upvotes: 2