简体   繁体   中英

Java Swing - How to create utils classes on Swing components with generics

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...

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.

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.

If your JComboBox s always contains String, the syntax would be:

public static void setComboBoxDefaultWidth(JComboBox<String> cb)
{
    cb.setPrototypeDisplayValue("mmmmmmmmmmmmmmmmmmmmmmmmmm");
}

如果你想为任何类型的Generic保留JComboBox,你不能。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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