Search code examples
javauser-interfacejavafxresizefxml

How to limit how much the user can resize a JavaFX window?


I am looking for ways to limit how much a user can resize the main window of my application, without preventing resizing completely. Specifically, I want to set minimum width and height for the window, and you'd think minWidth and minHeight would achieve this, but apparently they do not.

The root element of my window (declared in fxml) looks like this:

<VBox xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml"
      fx:controller="com.my.module.FXMLController"
      minWidth="400.0">
    <!-- ... -->
</VBox>

But all that minWidth seems to be doing is setting up the initial size of the window. If I try to resize the window as a user, i can get it as small as the title bar decorations, which is not ideal.

What's the correct way to do this, and is there a declarative way, as opposed to forcibly restoring the window's state after the user resizes it "illegally"? Furthermore, I would like to do this through the FXML document rather than in code, if possible.

For context, this is JavaFX 12 on JVM 12, I'm on Windows 10.
I had found another similar question on SO but it's unanswered and rather old.


Solution

  • Stage has width & height property and you can use Stage.setMinWidth() and .setMinHeight().

    You can also listen resize event like this,

    mainStage.widthProperty().addListener((o, oldValue, newValue)->{
        if(newValue.intValue() < 400.0) {
            mainStage.setResizable(false);
            mainStage.setWidth(400);
            mainStage.setResizable(true);
        }
    });