在 通常的 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