JavaFX 场景 minWidht 和 minHeight 不起作用

问题描述 投票:0回答:1

我尝试了以下 2 种方法来设置 JavaFX 中 AnchorPane 的 minHeight 和 minWidth(使其在 1280x720 下无法调整大小):

来自控制器类(从 login-view.fxml 中的按钮调用,该按钮具有相同的高度和宽度的最小值和最大值,但仅限于本地,并且不会将任何内容传输到 admin-view.fxml)。

root、stage、scene在LoginController中声明了,但它们不是

root = FXMLLoader.load(getClass().getResource("admin-view.fxml"));
stage = (Stage) ((Node) event.getSource()).getScene().getWindow();


scene = new Scene(root);
stage.setScene(scene);
stage.setMinHeight(scene.getRoot().minHeight(-1));
stage.setMinWidth(scene.getRoot().minWidth(-1));

stage.setMinHeight(720);
stage.setMinWidth(1280);

在 admin-view.fxml 中

<VBox maxHeight="720.0" maxWidth="1280.0" minHeight="720.0" minWidth="1280.0" ...>
    <children>
    <VBox VBox.vgrow="ALWAYS" />
        <AnchorPane maxHeight="720.0" maxWidth="1280.0" minHeight="720.0" minWidth="1280.0">
    ... my code here ...
    <VBox VBox.vgrow="ALWAYS" />
    </children>
<VBox>

(我选择了相同的最小值和最大值,因为我在教程中看到这应该可行)。

但我的问题是窗口的大小以 1280x720 加载,但它的大小可以调整为 ~1260x690。

javafx fxml
1个回答
0
投票

因为你说:“我希望应用程序有调整大小的限制”。我假设您希望舞台具有恒定的最小尺寸,以便能够显示特定尺寸的内容(在示例中,我使用 600x400 的较小最小尺寸以便于测试),无论其中显示什么。

您需要做的是计算内容周围框架的尺寸,然后将舞台的最小尺寸设置为内容的最小尺寸加上框架尺寸。

尝试运行下面的示例应用程序并调整舞台大小,同时监视输出到控制台的大小值。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SizedStageApp extends Application {
    private static final double MIN_CONTENT_WIDTH = 600;
    private static final double MIN_CONTENT_HEIGHT = 400;

    @Override
    public void start(Stage stage) throws Exception {
        StackPane root = new StackPane();
        root.layoutBoundsProperty().addListener((observable, oldLayoutBounds, newLayoutBounds) ->
                System.out.println(
                        "New scene size: " + newLayoutBounds.getWidth() + " x " + newLayoutBounds.getHeight()
                )
        );

        root.setMinSize(MIN_CONTENT_WIDTH, MIN_CONTENT_HEIGHT);
        root.setPrefSize(800, 600);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();

        System.out.println("Initial stage size: " + stage.getWidth() + " x " + stage.getHeight());
        System.out.println("Initial scene size: " + scene.getWidth() + " x " + scene.getHeight());

        double FRAME_WIDTH = stage.getWidth() - scene.getWidth();
        double FRAME_HEIGHT = stage.getHeight() - scene.getHeight();

        stage.setMinWidth(MIN_CONTENT_WIDTH + FRAME_WIDTH);
        stage.setMinHeight(MIN_CONTENT_HEIGHT + FRAME_HEIGHT);

        System.out.println("Min stage size: " + stage.getMinWidth() + " x " + stage.getMinHeight());
    }

    public static void main(String[] args) {
        launch(args);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.