Nathan Howard Nathan is a Java/HTML5 developer. Nathan also enjoys writing technical blog-articles and playing games in his spare time.

Another Way to Listen for Object Changes in JavaFX

1 min read

At IDRSolutions we use JavaFX for several display modes in our Java PDF Viewer.

The Problem.

We recently encountered an issue when coding in a different View Mode (Page Flow). The issue was that we needed to only listen for when the user changes page and update other objects accordingly, however, the class which has the object which changes the page already has a setOnMouseDragged Listener which performed a bunch of tasks and dragging the mouse on a slider is what changes the page. Having more than one listener on the same object was not an option as it was causing multiple conflicts and anomalies.

The Solution.

A quick solution to get around this was that we have a DoubleProperty object which has a method to set a double value, we used this method to set the page number. We could then tie a ChangeListener to the DoubleProperty object and listen for when the page number changed and perform whatever was needed accordingly.

The Example.

Normally to listen for some interaction with an object you can do something like :

Button btn = new Button("Go Forward a Page");
btn.setOnAction(new EventHandler() {
    @Override
    public void handle(ActionEvent event) {
        pageNavigator.setPage(currentPage++);
    }
});

However, if you do not want to use the setOnActionListener, you can also listen for a ChangeEvent on a double value like so :

DoubleProperty pageNoProperty = new SimpleDoubleProperty();

//User navigates forward a page, update page changer object.
pageNoProperty.addListener(new ChangeListener() {
    @Override
    public void changed(ObservableValue o, Object oldVal, Object newVal) {
        pageNavigator.setPage(pageNoProperty.doubleValue());
    }
});

There are many ways to listen for a change in an object in JavaFX, this is just one of them, for more information on using Property Listeners, please visit Properties and Binding page.

Javafx_logo_color
JavaFX is part of our Java PDF Library Viewer alongside the Swing iteration

Thank you for reading, I hope you enjoyed this article and will find it of use. If you have any questions, please post them in the comments section below.

You may find some of my JavaFX articles of interest :



Our software libraries allow you to

Convert PDF to HTML in Java
Convert PDF Forms to HTML5 in Java
Convert PDF Documents to an image in Java
Work with PDF Documents in Java
Read and Write AVIF, HEIC, WEBP and other image formats
Nathan Howard Nathan is a Java/HTML5 developer. Nathan also enjoys writing technical blog-articles and playing games in his spare time.