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.