[英]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. 我设置了一个事件处理程序来记录鼠标单击的x,y坐标,但是我只需要记录一次。
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. 我希望事件处理程序在检索到x,y值后停止侦听,但不确定如何。 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. 但这不能写在if语句中,因此我不确定如何触发它。
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值后,我计划为另一个项目准备一个类似的代码块,并且需要确保:
Edit: This is the line I used to add my EventHandler 编辑:这是我用来添加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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.