我有一个简单的字段(实际上是一个属性):
private final SimpleObjectProperty<ObjectWithColor> colored;ObjectWithColor类有一个属性SimpleObjectProperty<Color>,因此它的名称。
好的,现在这个属性有时没有指向任何地方;我想要做的是让一个ObjectExpression<Color>返回colored的颜色,而不是空的,或者是黑色的。
我在构造函数中编写了以下代码:
colored = new SimpleObjectProperty<>();
ObjectExpression<Color> color= Bindings.when(colored.isNotNull()).then(colored.get().colorProperty()). otherwise(Color.BLACK);我不明白的是为什么我会让一个NullPointerException运行这一行代码。我知道有人打电话给我,但我不明白为什么。难道不应该只在着色为非空时才调用吗?
发布于 2013-11-08 00:37:50
>难道不应该只在着色为非空时才调用吗?
不是的。让我们对您的代码做一些类比:
SimpleObjectProperty<ObjectWithColor> colored = new SimpleObjectProperty<>();
colored.get().colorProperty();因为Property及其派生类都是包装器类,所以可以认为它是一个将(包装) fullName字段作为字符串的Person类。因此,对上述的类比:
Person person = new Person();
person.getFullName().toString();我们得到NullPointerException at getFullName().toString(),因为getFullName()返回null。
对于这两种比较,假设都是这样的;包装字段没有默认值,也没有在默认构造函数中初始化。
让我们继续这个假设。在这种情况下,我们可以通过
通过构造函数初始化值:
Person person = new Person("initial full name");
person.getFullName().toString();或呼叫策划人:
Person person = new Person();
person.setFullName("Foo Bar");
person.getFullName().toString();您的代码也是如此:
SimpleObjectProperty<ObjectWithColor> colored =
new SimpleObjectProperty<>(new ObjectWithColor(Color.RED));
colored.get().colorProperty();或
SimpleObjectProperty<ObjectWithColor> colored = new SimpleObjectProperty<>();
colored.set(new ObjectWithColor(Color.RED));
colored.get().colorProperty();我希望我已经正确地理解了你的问题。然而,另一方面,在“那不应该被称为只有当有色是非空的?”提示,当您实际检查lastSupplier.isNotNull()时,您正在讨论着色是非空的。我假设它是,而不是,它是一个错误,并根据当前的代码片段回答。
编辑:哦!那是个错误!
产生了这个问题。在javafx.beans.binding.When#then()提到的文档中,此方法返回:
the intermediate result which still requires the otherwise-branch因此,colored.get().colorProperty()语句必须是可访问的。通常情况下,可绑定的if-然后- the块是为下列用途而设计的:
SimpleObjectProperty<Double> doubleProperty = new SimpleObjectProperty();
ObjectExpression<Double> expression = Bindings.when(doubleProperty.isNotNull()).then(doubleProperty).otherwise(-1.0);
System.out.println(doubleProperty.getValue() + " " + doubleProperty.isNotNull().getValue() + " " + expression.getValue());
doubleProperty.setValue(1.0);
System.out.println(doubleProperty.getValue() + " " + doubleProperty.isNotNull().getValue() + " " + expression.getValue());输出:
null false -1.0
1.0 true 1.0因此,您可以定义一个初始默认值:
SimpleObjectProperty<ObjectWithColor> colored = new SimpleObjectProperty(new ObjectWithColor(Color.BLACK));或者可以在绑定中直接使用ObjectWithColor.colorProperty。
https://stackoverflow.com/questions/19848549
复制相似问题