在 通常的 Java Fx 的教程中, 都只是用一个普通的结点来绑定一个处理事件, 如建立一个圆,再在圆上绑定一个鼠标处理事件。可当程序复杂性提升,一个场景中的结点数不少的时候,再一个一个去绑定,那不得把程序员小哥哥给累死啊。怎么办了?能够用数组啊,但是数组元素的事件绑定和普通元素的事件绑定同样吗?java
Pane pane = new Pane(); Circle[][] circles = new Circle[6][6]; for(int i = 1; i <= 5; i++){ for(int j = 1; j <= 5; j++){ circles[i][j] = new Circle(i * 100 + 50, j * 100 + 50, 45 ); circles[i][j].setFill(new Color(1,1,1,0)); circles[i][j].setStroke(Color.BLACK); int finalI = i; int finalJ = j; circles[i][j].setOnMousePressed(e -> { System.out.println(finalI + " " + finalJ); }); pane.getChildren().add(circles[i][j]); } }
class myHandler implements EventHandler<MouseEvent> { private int x; private int y; @Override public void handle(MouseEvent mouseEvent) { System.out.printf("the circle position is (%d,%d)\n", x, y); } myHandler(int _x, int _y){ x = _x; y = _y; } }
测试了一下,若是将myHandler类中的x,y的访问权限设为public, 会致使点击全部的结点都会输出(5,5),不懂, 甩锅给JVM吧git