How to set preferred width and height in fxml dynamically based on javafx screen resolution

I am new to javafx. Is it possible to dynamically set the preferred width and height in the fxml file based on the screen resolution? I know how to get screen resolution and set it to stage:

Screen screen = Screen.getPrimary(); Rectangle2D bounds = screen.getVisualBounds(); stage.setWidth(bounds.getWidth()); stage.setHeight(bounds.getHeight()); 

My question is how to dynamically configure prefWidth and prefHeight in fxml files. I also want to know if I can programmatically change the values โ€‹โ€‹of the properties in the fxml file, I use the scene builder.

+1
source share
1 answer

You can (sort of) do it in FXML, but not with Scene Builder (as far as I know). You can use the fx:factory attribute to get the main screen and define it in the <fx:define> block. Then use expression snapping to bind prefWidth and prefHeight to the root panel to the width and height of the screen.

It looks like

MaximizedPane.fxml:

 <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.layout.StackPane?> <?import javafx.scene.control.Label?> <?import javafx.stage.Screen?> <StackPane xmlns:fx="http://javafx.com/fxml/1" prefWidth="${screen.visualBounds.width}" prefHeight="${screen.visualBounds.height}" > <fx:define> <Screen fx:factory="getPrimary" fx:id="screen"/> </fx:define> <Label text="A maximized pane"/> </StackPane> 

and here is a quick test harness:

 import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; public class MaximizedFXMLPane extends Application { @Override public void start(Stage primaryStage) throws IOException { Scene scene = new Scene(FXMLLoader.load(getClass().getResource("MaximizedPane.fxml"))); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 

(The reason there is no way to do this with Scene Builder is because it does not support any mechanism for inserting <fx:define> blocks into your FXML, by the way.)

+4
source

Source: https://habr.com/ru/post/1246608/


All Articles