1

我有一个简单的字段(确实是一个属性):

    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 。我知道这会被调用,但我不明白为什么。不应该只在有色不为空时调用吗?

4

1 回答 1

4

> 不应该只在有色不为空时调用吗?

不。让我们用你的代码做一些类比:

SimpleObjectProperty<ObjectWithColor> colored = new SimpleObjectProperty<>();  
colored.get().colorProperty();

由于 theProperty及其派生类都是包装类,因此可以将其视为具有(包装)fullName 字段为 String 的 Person 类。所以上面的类比:

Person person = new Person();
person.getFullName().toString();

我们在 getFullName().toString() 处得到 NullPointerException,因为 getFullName() 返回 null。

对于这两种比较,假设是;包装的字段没有默认值或未在默认构造函数中初始化。

让我们继续这个假设。
在这种情况下,我们可以通过构造函数初始化值来避免 NullPointerException :

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-then-else 块设计用于以下用途:

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。

于 2013-11-08T00:37:50.047 回答