简体   繁体   中英

How to remove an event handler?

This stage of my program has a map that is drawn to a canvas and the user is prompted to choose the location they would like an item to be placed.

I set up an event handler to record the x,y co-ordinates of the mouse click, but this is something I only need to record once.

This is my event handler currently:

EventHandler boatHandler = new EventHandler<javafx.scene.input.MouseEvent>(){
        public void handle(javafx.scene.input.MouseEvent event){
            newX = event.getSceneX();
            newY = event.getSceneY();
            System.out.printf("setOnMouseClicked X = %f, Y = %f\n", newX, newY);
            newX = Math.round(newX/16) *16;
            newY = Math.round(newY/16) *16;
            System.out.printf("Rounded to multiple of 16 X = %f, Y = %f\n", newX, newY);
            if(newX > 0 || newY > 0){
                gc.drawImage(wItemset[0], newX, newY);
            }
        }
    };

I would like the event handler to stop listening once I have retrieved the x,y values but I'm unsure as to how. From reading other's questions I've found that I could potentially remove the event handler using:

canvas.removeEventHandler(MouseEvent.MOUSE_PRESSED, boatHandler);

But this can't be written within the if statement, so I'm unsure as to how i would trigger it.

After the x,y values have been recorded, I plan to have a similar block of code for another item and I need to ensure that:

  1. The correct item is placed
  2. The x,y values are for that item and not the previous item

Edit: This is the line I used to add my EventHandler

canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, boatHandler);

you could trigger it within your event handler

it will be something like that

EventHandler boatHandler = new EventHandler<javafx.scene.input.MouseEvent>(){
        public void handle(javafx.scene.input.MouseEvent event){
        //code used for retrieving x,y values
        canvas.removeEventHandler(MouseEvent.MOUSE_PRESSED, this);

        }
}

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