在javaFX中填充网格的列之间

时间:2015-01-09 06:15:24

标签: javafx

我试图在javaFX程序中显示一个4列网格。这就是我设置网格的方式。

 GridPane gridPane = new GridPane();
 gridPane.setHgap(10); 
 gridPane.setVgap(10);
 ColumnConstraints c1 = new ColumnConstraints();
 c1.setPercentWidth(25);
 ColumnConstraints c2 = new ColumnConstraints();
 c2.setPercentWidth(25);
 ColumnConstraints c3 = new ColumnConstraints();
 c3.setPercentWidth(25);
 ColumnConstraints c4 = new ColumnConstraints();
 c4.setPercentWidth(25);
 gridPane.getColumnConstraints().addAll(c1,c2,c3,c4);

我已将标签和文本字段分别放在第1,3列和第2,4列中。问题是文本字段和下一个标签之间存在间隙,因此第二文本字段的宽度减小了。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

这是一个非常简单的Application using GridPane。它使用与您的示例相同的gridPane column constraints并具有Label'sTextField's

enter image description here

如果您担心Label和TextField之间的差距,您必须记住Gridpane的总宽度分为4个部分(每个25%)。 TextField填充空格,Label也填充空间,但我们只看到Text。

MVCE代码:

public class GridPaneExample extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        GridPane gridPane = new GridPane();
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        gridPane.setPadding(new Insets(10));
        ColumnConstraints c1 = new ColumnConstraints();
        c1.setPercentWidth(25);
        ColumnConstraints c2 = new ColumnConstraints();
        c2.setPercentWidth(25);
        ColumnConstraints c3 = new ColumnConstraints();
        c3.setPercentWidth(25);
        ColumnConstraints c4 = new ColumnConstraints();
        c4.setPercentWidth(25);
        gridPane.getColumnConstraints().addAll(c1, c2, c3, c4);

        gridPane.add(new Label("Profile ID"), 0, 0);
        gridPane.add(new TextField(), 1, 0);
        gridPane.add(new Label("Profile Name"), 2, 0);
        gridPane.add(new TextField(), 3, 0);
        gridPane.add(new Label("Transfer Object"), 0, 1);
        gridPane.add(new TextField(), 1, 1);
        gridPane.add(new Label("Class Name"), 2, 1);
        gridPane.add(new TextField(), 3, 1);
        primaryStage.setScene(new Scene(gridPane, 500, 500));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

如果您仍然无法调整代码并进行修复,请考虑修改代码并添加MCVE

答案 1 :(得分:0)

您可以使用ColumnConstraints class中的许多其他属性。您可能希望标签对齐;您可能还希望文本字段增长并填充空间,而标签只需要足够的空间来容纳文本。所以我会做类似的事情:

GridPane gridPane = new GridPane();
 gridPane.setHgap(10); 
 gridPane.setVgap(10);
 ColumnConstraints c1 = new ColumnConstraints();
 c1.setHalignment(HPos.RIGHT);
 c1.setHgrow(Priority.NEVER);
 ColumnConstraints c2 = new ColumnConstraints();
 c2.setHgrow(Priority.ALWAYS);
 c2.setFillWidth(true);
 ColumnConstraints c3 = new ColumnConstraints();
 c3.setHalignment(HPos.RIGHT);
 c3.setHgrow(Priority.NEVER);
 ColumnConstraints c4 = new ColumnConstraints();
 c4.setHgrow(Priority.ALWAYS);
 c4.setFillWidth(true);
 gridPane.getColumnConstraints().addAll(c1,c2,c3,c4);