JavaFX 2.2:如何将SimpleBooleanProperty的值设置为null?

3

如果我这样做:

BooleanProperty b = new SimpleBooleanProperty();
b.setValue(null);
System.out.println(b.getValue());

我收到输出:
false

如何将SimpleBooleanProperty的值设置为null?将SimpleBooleanProperty设置为nullBooleanProperty b = null;)是个不好的主意,因为我会使用绑定(binding)。

我找到了方法:

ObjectProperty<Boolean> b = new SimpleObjectProperty<Boolean>(null);
System.out.println(b.getValue());

运行正常。

我无法回答自己的问题,所以把它放在这里,请见谅。


为什么你想要将一个布尔属性的值设为 null - undefined
@mre 我需要3个状态:true(真)、false(假)和undetermined(未确定)。我想将Boolean的值设为null,而不是boolean - undefined
2个回答

7
SimpleBooleanProperty是对boolean(原始类型)的封装,null值会自动设置为默认值false。
如果你想允许null值,可以使用ObjectProperty<Boolean> b = new SimpleObjectProperty<> ();。缺点是你会失去默认的布尔绑定。
另外,你可以创建一个自定义类来覆盖现有的setValue实现,但这可能会比较复杂,因为它依赖于set(boolean)方法,该方法显然不能接受null...

2

我认为没有办法将值设置为 null。请看 BooleanProperty#setValue 的实现。

public void setValue(Boolean paramBoolean)
{
    set(paramBoolean == null ? false : paramBoolean.booleanValue());
}

这正是你所看到的行为。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接