是否可以将 VBox 与 JavaFX 中的首选项大小的 StackPane 中心对齐?

问题描述 投票:0回答:1

我有一个

VBox
,我需要将其与
StackPane
的中心对齐。同时我需要使
StackPane
使用盒子首选项尺寸。此外,我无法添加任何其他包装窗格,因为我使用框布局X/Y 来获取/设置其在
StackPane
内的位置。这是我的代码:

public class JavaFxTest7 extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        var testBox = new VBox(new Label("Foo"), new TextField());
        testBox.setPrefSize(200, 0);
        testBox.setStyle("-fx-background-color: yellow");

        var stackPane = new StackPane();
        stackPane.setStyle("-fx-background-color: red");
        stackPane.getChildren().add(testBox);
        stackPane.setAlignment(Pos.CENTER);

        Scene scene = new Scene(stackPane, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

如果运行它,您将看到 testBox 将具有堆栈窗格的 100% 宽度和高度。我可以使用

testBox.setMaxSize(200, 200)
限制 testBox 大小,但我需要使用首选大小。如果可以的话,谁能告诉我该怎么做吗?

java javafx
1个回答
0
投票

此解决方案使用

Pane
而不是
StackPane
。它使用数学将
VBox
设置为
Pane
的中心。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


/**
 * JavaFX App
 */
public class App extends Application {

    @Override
    public void start(Stage stage) {
        
        var testBox = new VBox(new Label("Foo"), new TextField());
        testBox.setPrefSize(400, 0);
        testBox.setStyle("-fx-background-color: yellow");
        
        var pane = new Pane();
        pane.setStyle("-fx-background-color: red");
        pane.getChildren().add(testBox);
        
        Scene scene = new Scene(pane, 1280, 800);
        stage.setScene(scene);
        stage.show();
        
        double paneWidth = pane.getWidth();
        double paneHeight = pane.getHeight();
        
        double vBoxWidth = testBox.getWidth();
        double vBoxHeight = testBox.getHeight();
        
        testBox.setLayoutX((paneWidth / 2.0) - (vBoxWidth / 2.0));
        testBox.setLayoutY((paneHeight / 2.0) - (vBoxHeight / 2.0));
    }

    public static void main(String[] args) {
        launch();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.