在 javaFX 中的网格列之间填充

Padding between columns of a grid in 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 列中。问题是文本字段和下一个标签之间存在间隙,因此第二个文本字段的宽度减小了。

我该如何解决这个问题?

这里很简单Application using GridPane。它使用与您的示例相同的 gridPane column constraints 并具有 Label'sTextField's

如果您担心Label 和TextField 之间的差距,您必须记住gridpane 的总宽度分为4 个部分(每个25%)。 TextField 填充 space,Label 也填充 space,但我们只看到 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

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

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);