首页 > 解决方案 > Javafx GridPane,如何使节点居中?(文字/标签)

问题描述

我正在尝试为我正在学习的课程学习 Javafx。我在从 HTML + ERB 模板过渡到 Javafx 框架(我是 Rails 开发人员)时遇到了很多困难。

出于某种原因,我无法在网格窗格中将标签节点居中。这是我的start方法:

@Override
    public void start(Stage stage) throws Exception {
        GridPane root = new GridPane();
        FlowPane leftbanner = new FlowPane();

        leftbanner.setPrefWidth(200);
        String bgStyle = "-fx-background-color: lightblue;"
                         + "-fx-background-radius: 0%;"
                         + "-fx-background-inset: 5px;";
        leftbanner.setStyle(bgStyle);

        root.add(leftbanner, 0, 0, 1, 1);
        root.add(createGridPane(), 1, 0, 1, 1);

        Scene scene = new Scene(root, 700, 500);
        stage.setTitle("Recommendify");
        stage.setScene(scene);
        stage.show();
    }

我正在使用该createGridPane方法来构建我的应用程序。以下是该方法的内容,其中包括我将标签居中的尝试:

public GridPane createGridPane() {
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10));
        grid.setHgap(10);
        grid.setVgap(10);

        Text txt = new Text("Recommendify");
        txt.setFont(Font.font("Dialog", FontWeight.BOLD, 12));
        GridPane.setHalignment(txt, HPos.CENTER);

        grid.add(txt, 0, 0, 1, 1);
        grid.add(new Separator(), 0, 1, 3, 1);

        return grid;
}

我也尝试过这里发布的这些解决方案:JavaFX alignment of Label in GridPane

我是否需要将此标签节点放入容器中才能使其在 GridPane 中居中?像 HBox 还是 VBox?

标签: javajavafx

解决方案


您的代码实际上没有任何问题。“Recommendify”文本在其单元格居中。但是,单元格不比文本本身宽。

您可以通过打开createGridPane()方法中的网格线来查看这一点:

grid.setGridLinesVisible(true);

截屏


要测试对齐,您可以添加ColumnConstraintsGridPane

grid.getColumnConstraints().add(new ColumnConstraints(150));

上面的语句将第一列的首选宽度设置为150. 这是新的结果:

截图 2

如您所见,Text节点正确居中。

编辑: 请记住,如果您希望将您添加到第二行的内容Text居中Separator,您还需要让它跨越 3 列。


推荐阅读