JavaFX:在SimpleIntegerProperty中存储null [英] JavaFX: Storing null in a SimpleIntegerProperty
问题描述
我有 SimpleIntegerProperty
,它应该能够存储 null
。但是,这是不可能的,如在 IntegerProperty :
I have a SimpleIntegerProperty
which should be able to store null
. However, this is not possible, as written in the JavaDoc of IntegerProperty:
注意:将此属性设置或绑定到
null
value将属性设置为0.0。参见setValue(java.lang.Number)
。
Note: setting or binding this property to a
null
value will set the property to "0.0". SeesetValue(java.lang.Number)
.
这也适用于其他属性,例如 LongProperty
, FloatProperty
, DoubleProperty
,和 BooleanProperty
(但不是 StringProperty
,它允许 null
!)。为什么会这样?是否有解决方法在这些属性中存储 null
?
This also applies to other properties, such as LongProperty
, FloatProperty
, DoubleProperty
, and BooleanProperty
(but not to StringProperty
, which allows null
!). Why is this the case? Is there a workaround to store null
in these properties?
推荐答案
IntegerProperty.setValue(java.lang.Number)
方法在接口中指定 WriteableIntegerValue 和 WriteableValue 。 WriteableIntegerValue ,声明:
The IntegerProperty.setValue(java.lang.Number)
method is specified in the interfaces WriteableIntegerValue and WriteableValue. The JavaDoc of WriteableIntegerValue, states:
注意:此方法应接受
null
没有抛出异常,而是设置为0。
Note: this method should accept
null
without throwing an exception, setting "0" instead.
如果你正在查看 IntegerPropertyBase
类,您还可以看到该值实际存储为原始 int
(永远不能 null
)。这也在 SimpleIntegerProperty的JavaFX API中指定。 :
If you are looking at the code of the IntegerPropertyBase
class, you can also see that the value is actually stored as a primitive int
(which never can be null
). This is also specified in the JavaFX API of SimpleIntegerProperty:
此类提供包含
int的Property的完整实现
价值。
This class provides a full implementation of a Property wrapping a
int
value.
解决方案:
您可以简单通过使用 SimpleObjectProperty< Integer>
而不是 SimpleIntegerProperty
来绕过它,作为 SimpleObjectProperty
允许 null
值
Solution:
You can simply circumvent that by using a SimpleObjectProperty<Integer>
instead of a SimpleIntegerProperty
, as a SimpleObjectProperty
allows null
values
这篇关于JavaFX:在SimpleIntegerProperty中存储null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!