8

I have a SimpleIntegerProperty which should be able to store null. However, this is not possible, as written in the JavaDoc of IntegerProperty:

Note: setting or binding this property to a null value will set the property to "0.0". See setValue(java.lang.Number).

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?

user7291698
  • 1,972
  • 2
  • 15
  • 30
  • The primitive wrapper type, `IntegerProperty`, `DoubleProperty`, etc, are intended as exactly that: observable wrappers for primitive types. So `IntegerProperty` is intended to wrap an `int`, which of course cannot take on a `null` value. For convenience, `IntegerProperty` implements `Property`, so it inherits the `setValue(Number)` method; however it is not intended to be used to set the value to `null` (and as you observed, is documented to set the value to a default of `0`). If you want an observable that can take on `null`, use `ObjectProperty`. – James_D Feb 10 '17 at 13:50

1 Answers1

10

The IntegerProperty.setValue(java.lang.Number) method is specified in the interfaces WriteableIntegerValue and WriteableValue. The JavaDoc of WriteableIntegerValue, states:

Note: this method should accept null without throwing an exception, setting "0" instead.

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:

This class provides a full implementation of a Property wrapping a int value.

Solution: You can simply circumvent that by using a SimpleObjectProperty<Integer> instead of a SimpleIntegerProperty, as a SimpleObjectProperty allows null values

Community
  • 1
  • 1
user7291698
  • 1,972
  • 2
  • 15
  • 30