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?
You can do it with stage. setResizable(false); You can also remove window buttons with stage. initStyle(StageStyle. UNDECORATED);
You can set the value to this property using the setPreserveRatio() method. By default, the value of this property is true, i.e. though you change the width or height of the image, the aspect ratio of the displayed image will be the same as the source.
JavaFX Scene Builder is a visual layout tool that lets users quickly design JavaFX application user interfaces, without coding.
> 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With