【问题标题】:How to access a cell that is generated in a GridPane?如何访问在 GridPane 中生成的单元格?
【发布时间】:2016-10-05 04:14:37
【问题描述】:

我需要在我的 GridPane 中的特定单元格(中间居中的单元格)中添加一个形状。

这就是我的 GridPane 中单元格 (StackPane) 的制作方式:

private StackPane createCell() {
    StackPane cell = new StackPane();
    cell.getStyleClass().add("cell");
    return cell;
}

我已经尝试使用这种方法获得居中的单元格:

private Node getCenteredNodeGridPane(GridPane gridPane, int col, int row) {
    for (Node node : gridPane.getChildren()) {
        if (GridPane.getColumnIndex(node) == col/2 && GridPane.getRowIndex(node) == row/2) {
            return node;
        }
    }
    return null;
}

然后,获取节点:

Node centeredNode = getCenteredNodeGridPane(grid, 20, 20);
centeredNode ...... ??????

但我无法访问此节点的实际 StackPane。 我需要类似的东西,

centeredNode.getChildren().add(shape);

【问题讨论】:

    标签: javafx


    【解决方案1】:

    假设您只添加StackPanes 作为网格窗格的子节点,您只需要转换结果:

    StackPane centeredNode = (StackPane) getCenteredNodeGridPane(grid, 20, 20);
    

    根据您的具体要求,您当然可以在 getCenteredNodeGridPane 方法中执行此操作,并添加类型检查:

    private StackPane getCenteredNodeGridPane(GridPane gridPane, int col, int row) {
        for (Node node : gridPane.getChildren()) {
            if (node instanceof StackPane 
             && GridPane.getColumnIndex(node) == col/2 
             && GridPane.getRowIndex(node) == row/2) {
                return (StackPane) node;
            }
        }
        return null;
    }
    

    【讨论】:

    • 像往常一样令人惊叹的詹姆斯。我的尊重:)
    猜你喜欢
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2016-01-27
    • 1970-01-01
    • 2018-06-16
    • 2022-01-11
    相关资源
    最近更新 更多