我正在尝试为我正在参加的课程学习Javafx。我很难从超文本标记语言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;
}
我还尝试了这里发布的这些解决方案:GridPane中Label的JavaFX对齐
我是否需要将此Label节点放入容器中以使其在GridPane中居中?像HBox或VBox一样?
您的代码实际上没有问题。“推荐”文本在其单元格中居中。但是,单元格并不比文本本身宽。
您可以通过打开createGridPane()
方法中的网格线来看到这一点:
grid.setGridLinesVisible(true);
要测试对齐方式,您可以将ColumnConstraint
添加到GridPane
:
grid.getColumnConstraints().add(new ColumnConstraints(150));
上面的语句将第一列的首选宽度设置为150
。这是新结果:
如您所见,Text
节点正确居中。
编辑:请记住,如果您希望您的Text
在您添加到第二行的分隔符
上居中,您还需要让它跨越3列。