我创建了一个应用程序,该应用程序使用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();
}
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);
}
}
}
答案 0 :(得分:1)
您可以将鼠标事件处理程序添加到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()