Wednesday, December 10, 2014

Stackoverflow in JavaFX ChangeListeners

JavaFXs ChangeListeners are an easy way to monitor changes on JavaFX Properties and do some work if a change happened. But as easy as that is you easily can run into a stackoverflow because you'd changed the monitored property inside the ChangeListener.
Imagine you like to sort a Collection every time it is modified. Do sorting inside the ChangeListener raises a Stackoverflow because the sort itself raises a change event. So, how can we prevent that? The answer is simple: remove the ChangeListener before the code that modifies the property and then add it again!

public void onChanged(javafx.collections.ListChangeListener.Change<? extends Pair<String, L>> change){
        change.getList().removeListener(this);
        Collections.sort(change.getList(), comparator());
        change.getList().addListener(this);
    }


In this example we monitor a list and sort it when its content changes.

No comments: