我创建了一个应用程序,它使用 GridPanel 生成一个带有网格图案的板,该板由在 javaFX 中保存方形对象的节点组成。以下是当前输出:我想知道在点击节点后如何返回节点的坐标。我知道我必须使用各种动作侦听器,但在节点坐标方面我并不完全熟悉。下面是目前的源代码,非常感谢。import javafx.application.Application;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.layout.StackPane;import javafx.scene.paint.Color;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class MainApp extends Application { private final double windowWidth = 1000; private final double windowHeight = 1000; /*n is amount of cells per row m is amount of cells per column*/ private final int n = 50; private final int m = 50; double gridWidth = windowWidth / n; double gridHeight = windowHeight / m; MyNode[][] playfield = new MyNode[n][m]; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { Group root = new Group(); // initialize playfield for( int i=0; i < n; i++) { for( int j=0; j < m; j++) { // create node MyNode node = new MyNode( i * gridWidth, j * gridHeight, gridWidth, gridHeight); // add node to group root.getChildren().add( node); // add to playfield for further reference using an array playfield[i][j] = node; } } Scene scene = new Scene( root, windowWidth, windowHeight); primaryStage.setScene( scene); primaryStage.show(); primaryStage.setResizable(false); primaryStage.sizeToScene(); }
1 回答
守候你守候我
TA贡献1802条经验 获得超10个赞
您可以将鼠标事件处理程序添加到 root :
root.setOnMousePressed(e->mousePressedOnRoot(e));
其中mousePressedOnRoot(e)定义为
private void mousePressedOnRoot(MouseEvent e) {
System.out.println("mouse pressed on (x-y): "+e.getSceneX()+"-"+e.getSceneY());
}
编辑:或者,您可以通过添加 到其构造函数来将鼠标事件处理程序添加到每个MyNode实例。setOnMousePressed(e->mousePressedOnNode(e));
并添加方法:
private void mousePressedOnNode(MouseEvent e) {
System.out.println("mouse pressed on (x-y): "+e.getSceneX()+"-"+e.getSceneY());
}
如果您需要单击节点内的坐标,请使用e.getX()和e.getY()
添加回答
举报
0/150
提交
取消