3

我有一个 Utils 类,这样:

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

问题是这会导致编译器警告:

JComboBox 是一种原始类型。应该参数化对泛型类型 JComboBox 的引用

我不确定如何参数化泛型,以便调用方法和函数都可以工作(没有编译器错误)。无论出于何种原因,我可以解决一个问题,但不能同时解决这两个问题...

4

4 回答 4

4

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

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.

于 2012-10-05T01:11:06.703 回答
2

原型显示值必须与键入 JComboBox 的类型相同。

给定 a ,只有知道类型JComboBox<E>才能调用该方法。setPrototypeDisplayValue(E prototypeDisplayValue)因此,不能使用通配符 (?)。目前,您所能做的就是拥有:

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

您可能拥有的另一个选择是:

public static <E> void setComboBoxDefaultWidth(JComboBox<E> cb, E prototypeValue) {
    cb.setPrototypeDisplayValue(prototypeValue);
}

但这是没有意义的。

于 2012-10-05T07:27:26.577 回答
1

If your JComboBoxs always contains String, the syntax would be:

public static void setComboBoxDefaultWidth(JComboBox<String> cb)
{
    cb.setPrototypeDisplayValue("mmmmmmmmmmmmmmmmmmmmmmmmmm");
}
于 2012-10-05T01:10:50.183 回答
0

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

于 2012-10-07T04:27:12.803 回答