更新JavaFx网格大小

时间:2018-04-09 10:01:03

标签: java javafx fxml

如何更改JavaFx网格?我希望能够添加/删除行/列,但我不知道该怎么做。

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

所以我尝试添加新的行/列。除了我在Scenebuilder中应用的大小调整将被扭曲,我的旧行/列不会被删除。我如何删除旧的并更换它们,保持正确的尺寸属性?

我已经尝试了这个,但除了添加1个新行/列外,它对我没有任何作用

1 个答案:

答案 0 :(得分:1)

假设您只想更新约束而不是孩子,您应该只需更新rowConstraintscolumnConstraints更新任何其他列表的方式(即使用{{1 }和clear):

add

注意: 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); } } } 没有按预期执行操作:它会将您传递的所有元素作为varargs参数删除到列表中。您不会传递代码中的任何元素,并且方法调用不会修改列表。