【问题标题】:How to access a node inside of a GridPane in java如何在java中访问GridPane内的节点
【发布时间】:2016-12-03 01:41:07
【问题描述】:

我正在动态生成一个列数和行数相等的方形 GridPane。我正在使用 Rectangle 对象填充 GridPane 的每个索引。我需要做的就是在特定(列、行)索引处更改这些 Rectangle 对象之一的颜色。我看到了解决这个问题的两种方法。

  1. 检索对象并使用 setFill() 方法直接更改其颜色。

  2. 移除目标索引处的矩形,创建一个新的矩形,然后插入新的。

如果有人对如何完成其​​中任何一项有任何想法,我将不胜感激。

【问题讨论】:

标签: java javafx


【解决方案1】:

您当然可以将这些Rectangles 存储在Rectangle[][] 数组中,数组索引与GridPane 索引匹配,这样您就可以使用给定的索引轻松访问元素。

不过,您也可以使用 GridPane 的布局参数来识别孩子

for (Node child : gridPane.getChildren()) {
    Integer r = GridPane.getRowIndex(child);
    Integer c = GridPane.getColumnIndex(child);
    int row = r == null ? 0 : r;
    int column = c == null ? 0 : c;
    if (row == searchRow && column == searchColumn && (child instanceof Rectangle)) {
        Rectangle rect = (Rectangle) child;

        // do something with rect

        break;
    }
}

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多