java - 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?
解决方案
您的代码实际上没有任何问题。“Recommendify”文本在其单元格中居中。但是,单元格不比文本本身宽。
您可以通过打开createGridPane()
方法中的网格线来查看这一点:
grid.setGridLinesVisible(true);
要测试对齐,您可以添加ColumnConstraints
到GridPane
:
grid.getColumnConstraints().add(new ColumnConstraints(150));
上面的语句将第一列的首选宽度设置为150
. 这是新的结果:
如您所见,Text
节点正确居中。
编辑: 请记住,如果您希望将您添加到第二行的内容
Text
居中Separator
,您还需要让它跨越 3 列。
推荐阅读
- node.js - 使用 NGINX 在端口 80 上为带有虚拟主机的 Amazon EC2 上托管的域的 node.js 应用程序提供 HTTP 流量
- javascript - 从记录集量角器中获取值
- c - 显示正确的输出后正在打印不需要的输出
- django - 工作假期计划者 Web 应用程序
- php - 如何使用 Ajax 在 Codeigniter 中发布数据
- linux - 如何在 jmeter 中使用 OS Sampler 进行远程脚本
- owl - swrlapi:无效的 SWRL 原子谓词“人”
- spring - Spring Boot 和 JPA
- amazon-s3 - 我可以在交付到 S3 之前在 Kinesis Firehose 中自定义分区吗?
- java - Java 在特定索引之前和之后插入一个元素