我将GridPane用于JavaFX布局,并且始终对ColumnConstraints使用宽度百分比,但是在一种特定情况下,它似乎不起作用:当我在数组内设置ColumnConstraints的宽度百分比时。

我的代码:

ColumnConstraints[] myColumns = Factory.createColumns(3);
myColumns[0].setPercentWidth(35);
myColumns[1].setPercentWidth(12);
myColumns[2].setPercentWidth(53);
devicePane.getColumnConstraints().setAll(myColumns);


该数组来自我的实用程序方法,该方法使用相等划分的大小来创建列:

public static final ColumnConstraints[] createColumns(int count) {

    ColumnConstraints[] columns = new ColumnConstraints[count];

    ColumnConstraints column = new ColumnConstraints(1, 10, Double.MAX_VALUE);
    column.setPercentWidth(100/count);
    column.setFillWidth(true);
    column.setHgrow(Priority.ALWAYS);
    column.setHalignment(HPos.CENTER);

    for(int i = 0; i < count; i++) {

        columns[i] = column;

    }

    return columns;

}


结果:
Columns with old width percentage

但预期是:
Columns with right width percentage

最佳答案

您只是在创建一个ColumnConstraints对象。这使得无法为percentWidth属性分配不同的值。为此,您需要创建单独的对象:

public static final ColumnConstraints[] createColumns(int count) {
    ColumnConstraints[] columns = new ColumnConstraints[count];

    for(int i = 0; i < count; i++) {
        ColumnConstraints column = new ColumnConstraints(1, 10, Double.MAX_VALUE);
        column.setPercentWidth(100/count); // do we still need this?
        column.setFillWidth(true);
        column.setHgrow(Priority.ALWAYS);
        column.setHalignment(HPos.CENTER);
        columns[i] = column;
    }

    return columns;
}

08-05 19:07