简体   繁体   中英

JavaFX Eventhandler on several objects

I did a JavaFX Application with a gridpane containing Rectangles:

private GridPane addGridPane() {

    GridPane grid = new GridPane();
    grid.setHgap(2);
    grid.setVgap(2);
    grid.setPadding(new Insets(0, 0, 10, 0));

    int rows = 5;
    int cols = 5;

    for(int i=1; i<=rows; i++) {
        for(int j=1; j<=cols; j++) {
            r = new Rectangle(70, 70, Color.AQUA);
            grid.add(r, j, i);
        }
    } 
    return grid;
}

Now I want a Rectangle to be filled red, when the mouse is clicked on that Rectangle. For that I tried to put that into the second for loop:

r = new Rectangle(70, 70, Color.AQUA);
r.setOnMouseClicked(new EventHandler<MouseEvent>()
  {
      @Override
      public void handle(MouseEvent t) {
        r.setFill(Color.RED);
      }
  });
grid.add(r, j, i);

It seems, that every Rectangle has it's EventHandler, but only the last Rectangle is filled red. Is there a problem with the Event Target?

This works as expected for me (note the local variable r):

   for(int i=1; i<=rows; i++) {
            for(int j=1; j<=cols; j++) {
                Rectangle r = new Rectangle(70, 70, Color.AQUA);
                r.setOnMouseClicked(new EventHandler<MouseEvent>()
                {
                    @Override
                    public void handle(MouseEvent t) {
                        r.setFill(Color.RED);
                    }
                });
                grid.add(r, j, i);
            }
        }

The problem is that r is a field of some enclosing object. All handlers refer to that field, instead of the rectangle they were attached to. After the for loop, the field r holds the last rectangle, that's why only the last rectangle is filled red.

The solution is to declare r as a local variable in the for loop:

for(int i=1; i<=rows; i++) {
    for(int j=1; j<=cols; j++) {
        Rectangle r = new Rectangle(70, 70, Color.AQUA);
        r.setOnMouseClicked(new EventHandler<MouseEvent>()
          {
              @Override
              public void handle(MouseEvent t) {
                r.setFill(Color.RED);
              }
          });
        grid.add(r, j, i);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM