如何删除事件处理程序? [英] 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.
我设置了一个事件处理程序来记录鼠标单击的x,y坐标,但这是我只需要记录一次的事情.
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);
}
}
};
检索到x,y值后,我希望事件处理程序停止侦听,但不确定如何.通过阅读其他人的问题,我发现我可以使用以下方式删除事件处理程序:
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);
但这不能写在 if 语句中,因此我不确定如何触发它.
But this can't be written within the if statement, so I'm unsure as to how i would trigger it.
记录完x,y值后,我打算为另一个项目准备一个类似的代码块,并且需要确保:
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:
- 放置正确的物品
- x,y值用于该项目,而不是前一项
修改:这是我用来添加EventHandler的行
This is the line I used to add my EventHandler
canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, boatHandler);
推荐答案
您可以在事件处理程序中触发它
you could trigger it within your event handler
会是这样的
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);
}
}
这篇关于如何删除事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!