Site iconJava PDF Blog

How to add a window resize listener to JavaFX scene

While converting the PageFlow mode from Java3D to JavaFX in our Java PDF Viewer, one of the things that I found unclear was how to listen out for window resizes.

In awt, you are able to add a ComponentListener to the JPanel, and then override the componentResized() method to get the new width and height like so:

addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
System.out.println("New width: " + getWidth() + " New height: " + getHeight());
}
});

Unfortunately, neither the JavaFX Stage or Scene has any such listener you can use.

My next thought, having just added EventHandlers for mouse events to the scene, was that I would be able to add an EventHandler for a scene resize to the scene. But, unfortunately there is no such event to listen to.

scene.setOnMousePressed(EventHandler<MouseEvent>);// Adding a MouseEvent listener
scene.setOnWindowResize(EventHandler<WindowListener>);// Does not exist :(

The correct way to listen for window resizes is to add a ChangeListener to the width and height properties of the scene, like so:

scene.widthProperty().addListener(new ChangeListener<Number>() {
    @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth, Number newSceneWidth) {
        System.out.println("Width: " + newSceneWidth);
    }
});
scene.heightProperty().addListener(new ChangeListener<Number>() {
    @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneHeight) {
        System.out.println("Height: " + newSceneHeight);
    }
});

If you are using a JFXPanel, you could add a ComponentListener in the same way you would to a JPanel, but if you are modifying things on the scene, it would be preferable to use the method above to simplify things by keeping the listener on the correct thread.

I have written several articles on converting our Java3D usage into JavaFX and you can read the other articles here.