【问题标题】:JavaFX How to Center Multiple Components side by sideJavaFX 如何将多个组件并排居中
【发布时间】:2017-06-07 20:11:37
【问题描述】:

我有 2 个组件:LabelButton。我想将它们并排放置并在 CENTER 中对齐。但我没有这样做,因为它们仍然是左对齐而不是居中。

我的代码如下:

Label sloganLbl = new Label("With cost as low as $1.99, you can own a fraction share of U.S. stock. No account yet?");
sloganLbl.getStyleClass().add("blue-small-font");


Button signUpBtn = new Button("Open account now");
signUpBtn.getStyleClass().add("green-btn-small-font");

GridPane topGrid = new GridPane();

topGrid.setHgap(20);
topGrid.add(sloganLbl, 0, 0);
topGrid.add(signUpBtn, 1, 0);
topGrid.setGridLinesVisible(true);

GridPane.setHalignment(sloganLbl, HPos.RIGHT);
GridPane.setHalignment(signUpBtn, HPos.LEFT);

BorderPane topBorder = new BorderPane();
topBorder.setPadding(new Insets(15, 10, 15, 10));
topBorder.setCenter(topGrid);

topBorder.getStyleClass().add("blue-small-font");
topGrid.getStyleClass().add("blue-small-font");

borderPane.setTop(topBorder);

问题是topBorder.setCenter(topGrid); 无法将内容居中居中。似乎topGrid 占据了整个宽度,而不仅仅是它的 2 列的总宽度。

如何实现居中对齐?谢谢!

【问题讨论】:

    标签: java javafx alignment javafx-8 gridpane


    【解决方案1】:

    您可以使用左侧和右侧的空白填充列更新GridPane

    ColumnConstraints leftFiller = new ColumnConstraints();
    leftFiller.setHgrow(Priority.ALWAYS); // Fills the space left on the left side
    ColumnConstraints rightFiller = new ColumnConstraints();
    rightFiller.setHgrow(Priority.ALWAYS); // Fills the space left on the right side
    topGrid.getColumnConstraints().addAll(leftFiller, new ColumnConstraints(), 
        new ColumnConstraints(), rightFiller);
    
    topGrid.add(sloganLbl, 1, 0);
    topGrid.add(signUpBtn, 2, 0);
    

    这个 sn-p 将创建一个有 4 列的GridPane。当GridPane 调整大小时,第一个和最后一个正在增长,2 个内部列包含LabelButton

    请注意LabelButton 现在被放置在第二列和第三列中。

    【讨论】:

    • 非常酷的@DVarga,你的代码解决了我的问题。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多