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.

Ebook Page Link

The following two tabs change content below.
Leon is a Developer at IDRsolutions, focusing mainly on development of the PDF to HTML5/SVG converter. He was a speaker at JavaOne 2012, co-presenting a session titled 'Lessons Learned in Writing a PDF-to-JavaFX Converter for NetBeans'.

Related Posts:

Leon Atherton

About Leon Atherton

Leon is a Developer at IDRsolutions, focusing mainly on development of the PDF to HTML5/SVG converter. He was a speaker at JavaOne 2012, co-presenting a session titled 'Lessons Learned in Writing a PDF-to-JavaFX Converter for NetBeans'.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>