【问题标题】:JavaFX - Getting the index when clicking something inside a 2d ArrayJavaFX - 单击二维数组中的内容时获取索引
【发布时间】:2020-12-07 07:15:42
【问题描述】:

我已经构建了一个 ImageView 的二维数组,并且我希望能够在单击它时打印出 ImageView 的索引(并使用该信息来更改图片)。

我现在有以下代码,但我不知道如何让它在二维数组中打印其位置的 x 和 y 值。

ImageView[][] mainGrid = new ImageView[8][8]; 

...

for (int x = 0; x < 8; x++) {
    for (int y = 0; y < 8; y++) {
        mainGrid[x][y] = new ImageView(image);
        mainGrid[x][y].setOnMouseClicked(createMouseHandler());
    }
} 

...

private EventHandler<? super MouseEvent> createMouseHandler() {
    return event -> {
        System.out.println("Clicked");
    }
}

非常感谢任何帮助!谢谢!

【问题讨论】:

  • createMouseHandler(int x, int y) 怎么样?如果您不只是将其打印出来,请定义一个对象 (Cell),它表示一个数组元素并保存所有需要的信息:ImageViewxy。使用 Cell 对象数组:new Cell[8][8]

标签: arrays events javafx onclick imageview


【解决方案1】:

这个问题最通用的解决方法是使用Node类的getProperties()方法。您可以使用它将任何用户信息存储在您喜欢的节点中,然后在需要时检索它。在您的情况下,存储索引,然后在鼠标处理程序中检索它们。

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 2013-05-02
    • 2021-02-19
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多