Return 单击网格面板上的坐标

Return Coordinate on Click Grid Panel

我创建了一个应用程序,该应用程序使用 GridPanel 生成带有网格图案的板,该板由在 javaFX 中保存方形对象的节点组成。以下是当前输出:

我想知道如何 return 单击节点后获取节点的坐标。我知道我必须使用某种动作侦听器,但我对节点坐标并不完全熟悉。

下面是目前的源码,非常感谢

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();
    }

    public static class MyNode extends StackPane {

        public MyNode(double x, double y, double width, double height) {

            // create rectangle
            Rectangle rectangle = new Rectangle( width, height);
            rectangle.setStroke(Color.BLACK);
            rectangle.setFill(Color.LIGHTGREEN);

            // set position
            setTranslateX(x);
            setTranslateY(y);

            getChildren().addAll(rectangle);
        }
    }
}

您可以将鼠标事件处理程序添加到根目录:

  root.setOnMousePressed(e->mousePressedOnRoot(e));

其中 mousePressedOnRoot(e) 定义为

  private void mousePressedOnRoot(MouseEvent e) {
    System.out.println("mouse pressed on (x-y): "+e.getSceneX()+"-"+e.getSceneY());
  }

编辑: 或者,您可以通过将 setOnMousePressed(e->mousePressedOnNode(e)); 添加到其构造函数来将鼠标事件处理程序添加到每个 MyNode 实例。

并添加方法:

 private void mousePressedOnNode(MouseEvent e) {
        System.out.println("mouse pressed on (x-y): "+e.getSceneX()+"-"+e.getSceneY());
 }

如果您需要单击节点内的坐标,请使用 e.getX()e.getY()