JavaFX:在 SimpleIntegerProperty 中存储 null
JavaFX: Storing null in a SimpleIntegerProperty
我有一个 SimpleIntegerProperty
,应该可以存储 null
。但是,这是不可能的,正如 IntegerProperty 的 JavaDoc 中所写:
Note: setting or binding this property to a null
value will set the property to "0.0". See setValue(java.lang.Number)
.
这也适用于其他属性,例如 LongProperty
、FloatProperty
、DoubleProperty
和 BooleanProperty
(但不适用于 StringProperty
,它允许null
!)。为什么会这样?是否有在这些属性中存储 null
的解决方法?
IntegerProperty.setValue(java.lang.Number)
方法在接口 WriteableIntegerValue and WriteableValue. The JavaDoc of WriteableIntegerValue 中指定,声明:
Note: this method should accept null
without throwing an exception, setting "0" instead.
如果您正在查看 IntegerPropertyBase
class 的代码,您还可以看到该值实际上存储为原语 int
(which never can be null
). This is also specified in the JavaFX API of SimpleIntegerProperty:
This class provides a full implementation of a Property wrapping a int
value.
解决方法:
您可以简单地通过使用 SimpleObjectProperty<Integer>
而不是 SimpleIntegerProperty
来规避它,因为 SimpleObjectProperty
允许 null
值
我有一个 SimpleIntegerProperty
,应该可以存储 null
。但是,这是不可能的,正如 IntegerProperty 的 JavaDoc 中所写:
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
的解决方法?
IntegerProperty.setValue(java.lang.Number)
方法在接口 WriteableIntegerValue and WriteableValue. The JavaDoc of WriteableIntegerValue 中指定,声明:
Note: this method should accept
null
without throwing an exception, setting "0" instead.
如果您正在查看 IntegerPropertyBase
class 的代码,您还可以看到该值实际上存储为原语 int
(which never can be null
). This is also specified in the JavaFX API of SimpleIntegerProperty:
This class provides a full implementation of a Property wrapping a
int
value.
解决方法:
您可以简单地通过使用 SimpleObjectProperty<Integer>
而不是 SimpleIntegerProperty
来规避它,因为 SimpleObjectProperty
允许 null
值