JavaFX:区分单击和单击拖动

时间:2016-12-10 19:38:35

标签: java javafx eventhandler

我有多个标签。我有一个EventHandler<MouseEvent>,当单击Label时会启动一个方法(打开一个对话框)(setOnMouseClicked)。

但是,我还使用EventHandler实现了setOnMousePressed / setOnMouseDragged方法,以使Label可拖动。

我的问题是,当我在拖动后释放鼠标时,会调用鼠标单击方法并打开对话框。有没有办法区分这两个事件(即拖动时,不要打电话点击)? 或者是切换到不同组件(Button)的唯一方法,以便区分MouseEvent和ActionEvent?

2 个答案:

答案 0 :(得分:2)

对任何EventHandler使用一个MouseEvent,并在发生拖动时过滤点击事件。例如:

public class MyHandler implements EventHandler<MouseEvent> {

    private final EventHandler<MouseEvent> onDraggedEventHandler;

    private final EventHandler<MouseEvent> onClickedEventHandler;

    private boolean dragging = false;

    public Handler(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);
            }
        }

    }
}

然后将其添加到按钮:

button.addEventHandler(MouseEvent.ANY, 
                       new MyHandler(
                           e -> System.out.println("Dragged"), 
                           e -> System.out.println("Clicked"))
                       );

答案 1 :(得分:1)

也许通过使用另一个事件处理程序或过滤器,首先是特定的而不是通用的。

StackPane root = new StackPane();
root.addEventFilter(MouseEvent.MOUSE_PRESSED, 
 new EventHandler<MouseEvent>() {
 @Override
 public void handle(final MouseEvent event) {
  if(event.getEventType() == MouseEvent.MOUSE_PRESSED)
   //do something
 }
});

// or using MouseEvent.ANY in another eventhandler.
// registering an own eventdispatcher.