【问题标题】:Cannot instantiate ObservableList with an extractor无法使用提取器实例化 ObservableList
【发布时间】:2018-10-10 11:28:34
【问题描述】:

我有一个自定义对象FermentableInRecipe,它填充了TableView。为了响应列表中项目以及列表本身的更改,我决定使用提取器。这是我的ObservableList 的声明和实例化:

private ObservableList<FermentableInRecipe> fermentablesInRecipe = 
FXCollections.observableArrayList(item -> new Observable[]{item.WeightProperty()});

以下是我的自定义类的相关部分:

public class FermentableInRecipe {

    private DoubleProperty weight;

    ...

    public Double getWeight() {
         return this.weight.getValue();
    }

    public void setWeight(Double value) {
        this.weight.setValue(value);
    }

    public DoubleProperty WeightProperty() {
        if (weight == null) {
            weight = new SimpleDoubleProperty(0.0);
        }
        return weight;
    }

    ...
}

在我在下面提供的链接中,这种方法很有效。但是 Netbeans 告诉我 DoubleProperty 不能转换为 Observable。我可以理解为什么会这样,但我不明白为什么它在下面的链接中起作用而不是对我有用,以及如果这种方法不起作用,我应该如何创建提取器并将其链接到 weightProperty() 函数。

链接:

JavaFX 2.0 Choice Box Issue. How to update a choiceBox, which represents a list of objects, when an object is updated?

JavaFX, ObservableList: How to fire an InvalidationListener whenever an object of the list gets modified?

提前致谢。如果我遗漏了任何重要信息,请告诉我。

【问题讨论】:

  • “我明白为什么会这样” 我不明白:检查 Javadoc。这是All Implemented Interfaces中提到的第二个接口:docs.oracle.com/javase/9/docs/api/javafx/beans/property/… 你是否导入了正确的Observable 类,即javafx.beans.Observable
  • 可能您对 Observable 的导入有误
  • 你说的都是对的。我不小心导入了java.util.Observable 而不是javafx.beans.Observable。我不觉得自己像个白痴吗...

标签: java javafx java-8 observablelist extractor


【解决方案1】:

您编写的代码没有任何问题,这对我来说编译得很好:

import javafx.application.Application;
import javafx.beans.Observable;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.Stage;

public class JavaFXApplication1 extends Application {

    class FermentableInRecipe {

        private DoubleProperty weight;

        public Double getWeight() {
            return this.weight.getValue();
        }

        public void setWeight(Double value) {
            this.weight.setValue(value);
        }

        public DoubleProperty WeightProperty() {
            if (weight == null) {
                weight = new SimpleDoubleProperty(0.0);
            }
            return weight;
        }

    }

    private ObservableList<FermentableInRecipe> fermentablesInRecipe = FXCollections.observableArrayList(item -> new Observable[]{item.WeightProperty()});

    @Override
    public void start(Stage primaryStage) throws Exception {
    }
}

我建议仔细检查导入,并确保您没有错误地导入 java.util.Observable 或类似内容。

【讨论】:

  • 正确。我不小心导入了java.util.Observable 而不是javafx.beans.Observable。真丢人!并感谢您不厌其烦地编译代码。
  • @Joe 没问题,这发生在我们所有人身上......!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 2017-08-15
  • 2018-05-24
  • 2014-01-14
  • 1970-01-01
  • 2020-01-17
相关资源
最近更新 更多