【发布时间】:2018-11-05 21:20:25
【问题描述】:
我正在尝试为我正在学习的课程学习 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
我是否需要将此 Label 节点放入容器中才能使其在 GridPane 中居中?像 HBox 还是 VBox?
【问题讨论】:
-
顺便说一句,您的问题提到了
Label节点,但您的代码使用的是Text节点。无论哪种方式,结果都将是相同的,但您可能希望edit 该问题以避免混淆。 -
你正在使用
GridPane好吧。但是,你知道网格中有多少列和/行(网格通常表示行和列)。所以,计算有多少行/列,然后你想要你的标签/文本。顺便说一句,Label和Text有不同的用途。标签用于制作静态文本,Text用于创建可以在应用程序过程中更改的文本 - 例如状态栏文本。要在网格窗格的单元格中对齐Label,请使用:GridPane.setHalignment(labelToBeCentered, javafx.geometry.HPos.CENTER);。 -
此外,您似乎正在网格窗格中创建网格窗格 - (1)
GridPane root = new GridPane();在start中,(2) 在createGridPane()中将其添加到 @ 987654339@:root.add(createGridPane(), 1, 0, 1, 1);. -
以下是使用各种布局的示例:JavaFX: Working with Layouts.
-
@prasad_ - 我相信他们实际上打算拥有 2 个 GridPanes,一个在另一个中。