GridPane 不跨越整个 VBox

GridPane not spanning the whole VBox

我正在尝试创建一张稍后可以打印的发票。我正在使用 VBoxes 和 GridPanes 来做到这一点。中间 GridPane 的列数是可变的。我正在使用循环构建它。我尝试了很多不同的方法来使 GridPane(绿色边框)跨越整个 VBox(红色边框),但似乎没有任何效果。

设置边框后,我意识到网格实际上跨越了整个 VBox,但列并未占据整个 space。我不能给出列约束,因为我不知道中间网格的列数,我必须保持在 500px 以下。

下面是相关代码

final int width = 500;
BorderPane borderpane = new BorderPane();

VBox vboxTop = vboxForPrinting('l');
VBox vboxMiddle = vboxForPrinting('r');
VBox vboxBottom = vboxForPrinting('r');
GridPane gridpaneTop = new GridPane();
GridPane gridpaneMiddle = new GridPane();
GridPane gridpaneBottom = new GridPane();

borderpane.setPrefWidth(width);
vboxTop.setFillWidth(true);
vboxMiddle.setFillWidth(true);
vboxBottom.setFillWidth(true);

// Some code

vboxTop.getChildren().add(gridpaneTop);
vboxMiddle.getChildren().add(gridpaneMiddle);
vboxBottom.getChildren().add(gridpaneBottom);

borderpane.setTop(vboxTop);
borderpane.setCenter(vboxMiddle);
borderpane.setBottom(vboxBottom);

函数 vboxForPrinting() 如下:

public VBox vboxForPrinting(char align) {
    VBox vbox = new VBox();
    switch (align) {
        case 'r':
        case 'R':
            vbox.setAlignment(Pos.CENTER_RIGHT);
            break;
        case 'l':
        case 'L':
            vbox.setAlignment(Pos.CENTER_LEFT);
            break;
        default:
            vbox.setAlignment(Pos.CENTER);
    }
    vbox.setPadding(new Insets(5));
    vbox.setSpacing(5);
    vbox.setFillWidth(true);
    return vbox;
}

您可以为网格窗格的特定子项应用 setHgrow(),该子项将不断增长并占用剩余的可用空间 space。

来自 javadocs:

Sets the horizontal grow priority for the child when contained by a gridpane. If set, the gridpane will use the priority to allocate the child additional horizontal space if the gridpane is resized larger than it's preferred width. Setting the value to null will remove the constraint.

GridPane.setHgrow(name, Priority.ALWAYS);

其中,name 是一个 Label,您要将其扩展并占据剩余的空白位置。

如果您希望所有字段或列都增长,您可以将其应用于所有字段或您可以创建一个 ColumnConstraints 并将它们应用于 one/multiple 列。

下面的代码应该可以工作:

ColumnConstraints columnConstraints = new ColumnConstraints();
columnConstraints.setFillWidth(true);
columnConstraints.setHgrow(Priority.ALWAYS);
gridPane.getColumnConstraints().add(columnConstraints);

来到你的关心,

I can't give column constraints since I'm not aware of the number of columns of the middle Grid and I have to keep in under 500px.

好吧,您不需要跟踪列数,hgrow 只会在有额外 space 可用时允许子项增长。