I'm looking for a way to make a JavaFX pane always square no matter how the windows it's in is resized. The size should be determined by whatever is smaller, height or width. So it uses the maximum available space in whichever direction is smaller.
I made a simple example here:
This is the .fxml-File and I want paneInnerPane
to be square at all times.
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns="http://javafx.com/javafx/17.0.2-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.demo.MyController">
<center>
<VBox fx:id="vBoxCenter" BorderPane.alignment="CENTER">
<children>
<StackPane fx:id="stackPaneOuterPane" minHeight="800.0" minWidth="800.0">
<children>
<Pane fx:id="paneinnerPane" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: red;" />
</children>
</StackPane>
<ButtonBar prefHeight="40.0" prefWidth="200.0">
<buttons>
<Button mnemonicParsing="false" text="Button" />
<Button mnemonicParsing="false" text="Button" />
</buttons>
</ButtonBar>
</children>
</VBox>
</center>
</BorderPane>
This is the Controller and the main class:
public class MyController {
public VBox vBoxCenter;
public StackPane stackPaneOuterPane;
public Pane paneinnerPane;
@FXML
public void initialize() {
VBox.setVgrow(paneinnerPane, Priority.ALWAYS);
}
@FXML
private Label welcomeText;
@FXML
protected void onHelloButtonClick() {
welcomeText.setText("Welcome to JavaFX Application!");
}
}
public class MyApplication extends Application {
@Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(MyApplication.class.getResource("myview.fxml"));
Scene scene = new Scene(fxmlLoader.load());
stage.setTitle("Hello!");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
I tried thinks like this:
paneinnerPane.prefHeightProperty().bind(paneinnerPane.widthProperty());
paneinnerPane.prefWidthProperty().bind(paneinnerPane.heightProperty());
(Also with minWidth
and maxWidth
)
But the result is always the same:
The red rectangle should be square.
What do I have to do to make a Pane always be a square?