How can I adjust elements in my JavaFX program to the window size?

I want my labels to always be centered, regardless of the size of my window, and the left and right spacing to be the same. I'm using a BorderPane and an AnchorPane in the center? Should I use something else? I want my elements to constantly update/resize so they always adjust to the window size.
FXML:

 <?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Label?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.BorderPane?> <BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="578.0" prefWidth="460.0" xmlns=" http://javafx.com/javafx/21 " xmlns:fx=" http://javafx.com/fxml/1 " fx:controller="net.htlgkr.pos.lugerspreitzer.projekt_jfx_muehle.MenuController"> <center> <AnchorPane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER"> <children> <Label layoutX="218.0" layoutY="44.0" text="Start" /> <Label layoutX="218.0" layoutY="289.0" text="Chat" /> <Label layoutX="216.0" layoutY="219.0" text="Rules" /> <Label layoutX="215.0" layoutY="134.0" text="Game" /> <Label layoutX="190.0" layoutY="391.0" text="something else" /> </children> </AnchorPane> </center> </BorderPane>
1 vote, average: 1.00 out of 1 (1 rating, 1 votes, rated)
You need to be a registered member to rate this.
Loading...
Subscribe
Notify of
1 Answer
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
regex9
10 months ago

The elements of your window will not be responsive, just as you have them with an AnchorPane (or fixed variables and coordinates).

For an adaptive/responsive design, please note:

1) Use layout panes such as BorderPane , GridPane , FlowPane , HBox , TilePane , VBox

2) Dispense with fixed sizes. Instead, only set size ranges (eg minimum/maximum width). The selected size should align itself with the content ( Region.USE_COMPUTED_SIZE ).

You can use Constraints (see eg ColumnConstraints the GridPane ) also specify percentage values ​​or FXML calculate the values ​​accordingly.

Example:

 

About fx:factory the primary stage is referred. Thus it is possible to use the current window size ( visualBounds ) and on the basis of which the desired variables are calculated.

3) But what you should also consider: It is not necessarily practical to make elements automatically larger/smaller when scaling the window size. As with responsive websites, you should instead see how the elements are best arranged depending on the available space.

In this respect, you could also build your own grid layout, which is created in different breakpoints. In this Article the implementation of such a layout manager is shown.