Paul Avalos Paul Avalos - 4 months ago 11
Java Question

How do I now the generic wrapped value on a Property Change Listener on Java Fx?

I've got this code:

circle2.radiusProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("Change detected for " + observable);
circle1.setRadius(newValue.doubleValue());
}
});

final IntegerProperty lapCounterProperty = new SimpleIntegerProperty();
pathTransition.currentTimeProperty().addListener(new ChangeListener<Duration>() {

@Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {

}
});


How do I now what I should type in between <> on the ChangeListener?

Answer

The addListener method comes from ObservableValue<T>, which defines

void addListener(ChangeListener<? super T> listener)

while ChangeListener<S> defines:

void changed(ObservableValue<? extends S> observable, S oldValue, S newValue)

Keeping it simple (there usually isn't a reason not to), if you have a ObjectProperty<Duration> (which is what PathTransition#duration) is, you would want to use a ChangeListener<Duration>, which will have changed method with the signature:

void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue)

But you could also use a ChangeListener<T> for any T which is a supertype of Duration (Object, for example), while the changed method of the listener can accept an ObservableValue<T> for any T which extends Duration.

So the short answer is - if you have no good reason not to, always use the same type parameter of your ObservableValue for it's ChangeListener.

Comments