gpt4 book ai didi

JavaFX - ListView - 泛型 - CellFactory

转载 作者:行者123 更新时间:2023-12-02 11:15:11 24 4
gpt4 key购买 nike

我有:

public abstract class V {}

public class PV extends V {}

public class TV extends V {}

我还有:

ListView<? extends V> listView = new ListView<>();

当我尝试时:

listView.setCellFactory(new Callback<ListView<? extends V>, ListCell<? extends V>>() {
@Override
.............
});

我收到错误警告:

Incompatible types: 
anonymous Callback<ListView<? extends V>, ListCell<? extends V>>
cannot be converted to Callback<ListView<CAP#1>, ListCell<CAP#!>>
where CAP#1 is fresh type-variable:
CAP#1 extends V from capture of ? extends V

我尝试过:

new Callback<ListView<V>, ListCell<V>>() 

这并没有解决这个问题。

为什么我会收到该消息?有什么方法可以解决它吗?

最佳答案

cellFactory 需要 Callback<ListView<T>, ListCell<T>>,其中 TListView 的类型参数。

使用通配符无法指定确切的类型参数。此外,由于您的通配符将 T 限制为 V 的父类(super class)型,因此您不能使用 ListCell<? extends V> (即使不需要确切的类型, updateItem 接收与 ListCell 的类型参数匹配的值,也不能保证该类型是可分配的(确切的类型ListView 的参数可以是 ObjectListView 的参数可以是 PV ))。

您可以创建一个方法来创建 Callback,以防止通配符成为问题,但是 super 限制仍然没有什么意义,因为 ListCell 充当消费者。

public static <T> Callback<ListView<T>, ListCell<T>> forListView() {
return new Callback<ListView<T>, ListCell<T>>() {
@Override
public ListCell<T> call(ListView<T> lv) {
return new ListCell<T>() {

@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
setText((empty || item == null) ? "" : item.toString());
}

};
}
};
}
ListView<? super V> lv = ...;
lv.setCellFactory(forListView());

(您也可以对静态方法的 T 施加限制:public static <T super V> Callback<ListView<T>, ListCell<T>> forListView() )

关于JavaFX - ListView <?扩展 V> - 泛型 - CellFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50331796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com