Forum Stats

  • 3,815,576 Users
  • 2,259,053 Discussions
  • 7,893,172 Comments

Discussions

Why does DoubleProperty implement Property<Number> and not Property<Double>?

cayhorstmann
cayhorstmann Member Posts: 10
edited Sep 2, 2013 3:26AM in JavaFX 2.0 and Later

I am asking because it seems to be a bit inconvenient when implementing ChangeListeners.

For example,

slider.valueProperty().addListener((property, oldValue, newValue)
   -> message.setFont(new Font(newValue)));

does not work. I invite you find out the reason from the error message:

error: no suitable method found for addListener((property,[...]lue)))

      slider.valueProperty().addListener((property, oldValue, newValue)

                            ^

    method Observable.addListener(InvalidationListener) is not applicable

      (argument mismatch; incompatible parameter types in lambda expression)

    method ObservableValue.addListener(ChangeListener<? super Number>) is not applicable

      (argument mismatch; cannot type-check lambda expression with inferred parameter types

          inferred types: ObservableValue<? extends Number>,Number,Number)

That's actually bogus. newValue is inferred to be Number, and Number doesn't auto-unbox. This works:

slider.valueProperty().addListener((property, oldValue, newValue)
   -> message.setFont(new Font(newValue.doubleValue())));

So, that's all rather obscure. What was gained by having DoubleProperty implement Property<Number> and not Property<Double>?

Thanks,

Cay

Answers

  • Martin Sladecek-Oracle
    Martin Sladecek-Oracle Member Posts: 11 Employee

    This is the way it was done in previous version of FX to simplify the FX code and avoid tons of duplicated code. We've tried to fix this, but it was too late, as the cost of backward incompatibility was too hight.

    You can however use conversion methods to achieve this. Like this:

    slider.valueProperty().asObject().addListener(...)

This discussion has been closed.