我有Pane:
pane.addEventFilter(MouseEvent.ANY, new EventsHandler(e -> System.out.println(""), e -> {
createEvents(e.getX(), e.getY());
})});
方法createEvents:
Circle circle = new Circle(x, y, 5);
circle.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> System.out.println("Clicked!"));
pane.getChildren().add(circle);
当我点击一个圆圈时,它会调用两个事件:字符串单击并创建一个新事件。你怎么没有将点击事件传递给父母?
我的EvendsHandler添加窗格:
public class EventsHandler implements EventHandler<MouseEvent> {
private final EventHandler<MouseEvent> onDraggedEventHandler;
private final EventHandler<MouseEvent> onClickedEventHandler;
private boolean dragging = false;
public EventsHandler(EventHandler<MouseEvent> onDraggedEventHandler, EventHandler<MouseEvent> onClickedEventHandler) {
this.onDraggedEventHandler = onDraggedEventHandler;
this.onClickedEventHandler = onClickedEventHandler;
}
@Override
public void handle(MouseEvent event) {
if (event.getEventType() == MouseEvent.MOUSE_PRESSED) {
dragging = false;
} else if (event.getEventType() == MouseEvent.DRAG_DETECTED) {
dragging = true;
} else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
// maybe filter on dragging (== true)
onDraggedEventHandler.handle(event);
} else if (event.getEventType() == MouseEvent.MOUSE_CLICKED) {
if (!dragging) {
onClickedEventHandler.handle(event);
}}}}
答案 0 :(得分:1)
您正在使用事件过滤器。在从根到目标节点的遍历中调用过滤器。由于在调用节点自己的过滤器之前调用了祖先的所有过滤器,因此节点的过滤器不可能阻止父过滤器的执行。
您应该使用事件 处理程序 ,这些事件在从目标节点遍历到根节点时被调用,并允许您通过使用事件处理程序来阻止执行父事件处理程序事件:
pane.addEventHandler(MouseEvent.ANY, new EventsHandler(e -> System.out.println(""), e -> {
createEvents(e.getX(), e.getY());
})});
circle.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
System.out.println("Clicked!");
event.consume();
});
注意:如果您只为特定事件类型注册单个事件处理程序,则可以指定例如onMouseClicked
属性而非使用addEventHandler
:
circle.setOnMouseClicked(event -> {
System.out.println("Clicked!");
event.consume();
});