如何在保持宽高比的同时调整javafx.scene.Scene的大小? [英] How to make javafx.scene.Scene resize while maintaining an aspect ratio?

查看:1040
本文介绍了如何在保持宽高比的同时调整javafx.scene.Scene的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaFX 2.2.7-b01编写应用程序。

I'm writing an application with JavaFX 2.2.7-b01.

以下是我目前拥有的代码示例。如何调整应用程序窗口的大小,但保持最初配置的宽高比?换句话说,如果用户调整窗口大小,窗口宽度应始终保持窗口高度的两倍。

Here is an example of the code I currently have. How can I allow the application window to be resized but maintain the aspect ratio it is initially configured with? In other words, if the user resizes the window, the window width should always stay double the window height.

  ...
  public void showScene(Stage stage, String fxmlPath) {
    try {
      FXMLLoader loader = new FXMLLoader();
      loader.setBuilderFactory(new JavaFXBuilderFactory());
      loader.setLocation(fxmlPath);
      Parent page;
      try (InputStream in = Main.class.getResourceAsStream(fxmlPath)) {
        page = (Parent) loader.load(in);
      }
      Scene scene = new Scene(page, 400, 200);
      stage.setScene(scene);
      stage.sizeToScene();
      stage.show();
    } catch (Exception ex) {
      ...
    }
  }
  ...

似乎JavaFX允许用户在构造函数中指定场景的宽度和高度,但不允许以编程方式访问以更新宽度或高度。没有setWidth或setHeight方法。我知道我可以在调整大小时添加属性监听器来获取场景的只读宽度/高度,但我还是无法弄清楚如何动态更改场景尺寸所以我可以强制维持宽高比。

It seems JavaFX allows a user to specify the width and height of a scene in the constructor but does not allow programmatic access to update the width or height. There are no setWidth or setHeight methods. I know I can add property listeners to get the read only width/height of the scene while it is being resized, but I haven't been able to figure out how to change the scene dimensions dynamically so I can force the aspect ratio to be maintained.

我想如果我要继承Scene对象(如果我必须的话),这是可能的,但是有没有其他简单的方法吗?

I imagine this would be possible if I were to subclass the Scene object (if I have to I will) but is there any other simple way to do this?

推荐答案

> 如何使javafx.scene.Scene在保持宽高比的同时调整大小?

通过操纵舞台大小而不是场景: / p>

By manipulating the stage size instead of scene:

@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Play by resizing the window");
    VBox root = new VBox();
    root.getChildren().add(btn);
    root.setStyle("-fx-background-color: gray");

    Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.minWidthProperty().bind(scene.heightProperty().multiply(2));
    primaryStage.minHeightProperty().bind(scene.widthProperty().divide(2));
    primaryStage.show();
}

这篇关于如何在保持宽高比的同时调整javafx.scene.Scene的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆