Issue
I have an application in javaFX, I would like to know how it is possible to disable the resizable option, but not to disable the maximize button, because if I need to maximize the window.
I am using the following snippet:
stage.setResizable (false);
Solution
This solution is not realy pretty or 'clean code', but at least it's working:
You can achieve this by setting a minimum and maximum size to the stage, with the same value. That will cause the window to not be changed in size if the user tries to resize it. But because the resizable
property is still set to true
the maximize button is still enabled. Unfortunately the maximized window will also have the maximum size, that you entered, so it won't be realy maximized. To fix this you need to remove the maximum size from the stage as soon as the window is maximized (which is the ugly part of this solution).
You can do it like this:
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class MaximizableButNotResizableExample extends Application {
public static final int WIDTH = 600;
public static final int HEIGHT = 400;
//flag that indicates the window is re-maximized by the application (to prevent setting the maximum size when un-maximizing the stage)
private boolean reMaximize = false;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
try {
Parent root = new AnchorPane();
Scene scene = new Scene(root, WIDTH, HEIGHT);
primaryStage.setScene(scene);
primaryStage.show();
//set the stages maximum and minimum size so it can't be resized
primaryStage.setMinWidth(WIDTH);
primaryStage.setMaxWidth(WIDTH);
primaryStage.setMinHeight(HEIGHT);
primaryStage.setMaxHeight(HEIGHT);
//add a listener to the maximized property to disable the maximum size of the window when it gets maximized
primaryStage.maximizedProperty().addListener((observer, oldVal, newVal) -> {
if (newVal) {
//remove the maximum size when maximizing the stage
primaryStage.setMaxWidth(Integer.MAX_VALUE);
primaryStage.setMaxHeight(Integer.MAX_VALUE);
if (!reMaximize) {
//re-maximize the stage programmatically to make it realize there is no maximum size anymore
reMaximize = true;
primaryStage.setMaximized(false);
primaryStage.setMaximized(true);
}
reMaximize = false;
}
else {
//set the maximum size only if the un-maximize was caused by the user
if (!reMaximize) {
primaryStage.setMaxWidth(WIDTH);
primaryStage.setMaxHeight(HEIGHT);
}
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I realy hope javafx has a better solution for this, that I just haven't found, but if not, this workarround should also do.
Answered By - Tobias