【发布时间】:2021-11-24 11:47:30
【问题描述】:
我正在使用 JavaFX 开发扫雷游戏:
我的GridPane 是由ImageViews 组成的,我正试图找到一种方法来找出在GridPane 上单击的图像的列索引和行索引。我目前有这个代码:
gameGrid.setOnMouseClicked(event -> //gameGrid is my GridPane
{
Node source = (Node)event.getSource();
int columnIndex = GridPane.getColumnIndex(source);
System.out.println(columnIndex);
int rowIndex = GridPane.getRowIndex(source);
if(event.getButton()== MouseButton.PRIMARY)
game.newRevealCell(columnIndex,rowIndex);
else if(event.getButton()==MouseButton.SECONDARY)
game.getGrid()[columnIndex][rowIndex].setFlagged(true);
//game.getGrid is a 2D array containing the game cells
});
但是,getColumnIndex 和 getRowIndex 方法正在返回 null。我做错了什么?
【问题讨论】:
-
一个complicated solution using custom events。有比链接示例更简单的解决方案。它旨在演示创建和处理自定义事件,这不是解决此问题所必需的,但它确实提供了一种潜在的解决方案。
-
可能为每个“单元”添加唯一的事件处理程序会更容易(“单元”是您放置在网格窗格中的节点)。这样您就“只知道”与哪个单元格进行了交互,因为只有与该特定单元格交互才会调用该特定事件处理程序。
标签: java javafx mouseevent gridpane