如何修复 GridPane 上的标签堆叠在索引 (0,0) 上?它似乎忽略了我对该功能的输入

How to fix Labels on GridPane stacking on index (0,0)? It seems to be ignoring my input to the function

我正在尝试使用 GridPane 布局在 javafx 中创建一个基本的登录屏幕。问题是我放在网格上的所有标签都将定位 (0,0) 似乎忽略了我的列和行索引值。

我已经尝试将索引的极值放入两个函数调用中,但没有任何变化。它似乎忽略了我给它的任何索引并默认为 (0,0)。

网格窗格设置:

GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10));
grid.setVgap(10);
grid.setHgap(10);

函数调用标签:

// Name label
    Label nameLabel = new Label("Username:");
    GridPane.setConstraints(grid, 0, 0);     

// Password label
   Label passLabel = new Label("Password:");
   GridPane.setConstraints(grid, 0, 1);      

正在将 GridPane 添加到场景中:

grid.getChildren().addAll(nameLabel, nameInput, passLabel, passInput, loginButton);
Scene scene = new Scene(grid, 300, 200);

您使用的 GridPane.setConstraints(); 不正确。您应该在节点上设置约束,而不是在 grid 上设置约束。示例:

// Name label
Label nameLabel = new Label("Username:");
GridPane.setConstraints(nameLabel, 0, 0);     

// Password label
Label passLabel = new Label("Password:");
GridPane.setConstraints(passLabel, 0, 1);   

See javadocs for more details.