更新 JavaFx 网格大小

Update JavaFx grid size

如何更改我的 JavaFx 网格?我希望能够 add/remove rows/columns 但我不知道该怎么做。

<GridPane fx:id="gameGrid" gridLinesVisible="true" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="5.0">
          <columnConstraints>
            <ColumnConstraints hgrow="SOMETIMES" maxWidth="1.7976931348623157E308" minWidth="-Infinity" percentWidth="33.0" />
            <ColumnConstraints hgrow="ALWAYS" maxWidth="1.7976931348623157E308" minWidth="-Infinity" percentWidth="33.0" />
              <ColumnConstraints hgrow="SOMETIMES" maxWidth="1.7976931348623157E308" minWidth="-Infinity" percentWidth="33.0" />
          </columnConstraints>
          <rowConstraints>
            <RowConstraints maxHeight="1.7976931348623157E308" minHeight="-Infinity" percentHeight="33.0" vgrow="ALWAYS" />
            <RowConstraints maxHeight="1.7976931348623157E308" minHeight="-Infinity" percentHeight="33.0" vgrow="ALWAYS" />
            <RowConstraints maxHeight="1.7976931348623157E308" minHeight="-Infinity" percentHeight="33.0" vgrow="ALWAYS" />
          </rowConstraints>
           <children>
              <ImageView fitHeight="90.0" fitWidth="90.0" pickOnBounds="true" preserveRatio="true" GridPane.columnIndex="1" GridPane.halignment="CENTER" GridPane.rowIndex="1" GridPane.valignment="CENTER">
                 <image>
                    <Image url="@X.png" />
                 </image>
              </ImageView>
           </children>
        </GridPane>

我可以在这个功能中从我的控制器更改它吗?

public void updateGrid(int cols, int rows){
    gameGrid.getRowConstraints().removeAll();
    gameGrid.getColumnConstraints().removeAll();
    gameGrid.getColumnConstraints().add(new ColumnConstraints(cols));
    gameGrid.getRowConstraints().add(new RowConstraints(rows));
}

所以我尝试添加新的 rows/columns。除了我在 Scenebuilder 中应用的大小会被扭曲并且我的旧 rows/columns 不会被删除。我如何移除旧的并替换它们,同时保持正确的尺寸特性?

我试过了,但除了添加 1 个新的 row/column

之外,它对我没有任何作用

假设您只想更新约束,而不是子项,您应该按照更新任何其他列表的方式简单地更新 rowConstraintscolumnConstraints(即使用 clearadd):

public void updateGrid(int cols, int rows) {
    List<RowConstraints> rowList = gameGrid.getRowConstraints();
    rowList.clear();
    if (rows > 0) {
        RowConstraints rowConstraints = new RowConstraints();
        rowConstraints.setPercentHeight(100d / rows);
        for (int i = 0; i < rows; i++) {
            rowList.add(rowConstraints);
        }
    }

    List<ColumnConstraints> columnList = gameGrid.getColumnConstraints();
    columnList.clear();
    if (cols > 0) {
        ColumnConstraints columnConstraints = new ColumnConstraints();
        columnConstraints.setPercentWidth(100d / cols);
        for (int i = 0; i < cols; i++) {
            columnList.add(columnConstraints);
        }
    }
}

注意: removeAll 没有按照您的预期执行:它删除了您作为可变参数参数传递给列表的所有元素。您没有在代码中传递任何元素,并且列表没有被方法调用修改。