How to make javafx.scene.Scene resize while maintaining an aspect ratio?


Question

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) {
      ...
    }
  }
  ...

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.

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?

1
4
5/13/2013 11:49:57 PM

Accepted Answer

> How to make javafx.scene.Scene resize while maintaining an aspect ratio?

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();
}
4
9/5/2013 2:04:31 PM

In netbeans using Java Fx Scene Builder provide you can use AnchorPane Constraints to set Resizing of stage.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon