如何在允许最大化的同时禁用调整大小?

How to disable resizing while allowing maximizing?

我在 javaFX 中有一个应用程序,我想知道如何禁用可调整大小的选项,而不是禁用最大化按钮,因为如果我需要最大化 window。

我正在使用以下代码段:

stage.setResizable (false);

这个解决方案不是很漂亮或 'clean code',但至少它是有效的:

您可以通过为舞台设置 最小和最大大小 来实现这一点,并使用相同的值。如果用户尝试调整它的大小,这将导致 window 的大小不会改变。但是因为 resizable 属性 仍然设置为 true 最大化按钮仍然启用。不幸的是,最大化的 window 也将具有您输入的最大大小,因此它不会真正最大化。要解决此问题,您需要在 window 最大化后立即从舞台上删除最大尺寸(这是此解决方案的丑陋部分)。

你可以这样做:

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();
        }
    }
}

我真的希望 javafx 对此有更好的解决方案,我只是还没有找到,但如果没有,这个 workarround 应该也可以。