setOn“ Fast” Click-JavaFx

时间:2019-01-31 18:01:38

标签: javafx onclick onclicklistener

我有一个按钮,点击该按钮可以将其从屏幕上移开。问题是,当我进行拖放操作时,松开鼠标时会调用click事件,我尝试过:

setOnMouseClicked setOnAction setOnMousePressed

如何快速单击click函数,例如Android时间之所以会有所不同,因为我们有setOnLongClick,因此在进行拖放操作以及当我真正进行操作时会有所不同想点击吗?

例如:

要移动,请执行以下操作:

button.setOnMouseDragged(e -> {
     //code move
});

到eventClick:

button.setOnMouseClicked/ Action / MousePressed (e -> {
    //call method
});

但是当我放下它时,它调用setOnMouseClicked / Action / MousePressed,我想要的只是在我快速单击时调用它,当我放下拖放时不要调用。

enter image description here

1 个答案:

答案 0 :(得分:2)

一种选择是跟踪Button是否被拖动;如果不是,则仅在onAction处理程序中执行代码。这是一个示例:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

public class Main extends Application {

  private Point2D origin;
  private boolean wasDragged;

  @Override
  public void start(Stage primaryStage) {
    Button button = new Button("Drag me!");
    button.setOnAction(this::onAction);
    button.setOnMousePressed(this::onMousePressed);
    button.setOnMouseDragged(this::onMouseDragged);
    button.setOnMouseReleased(this::onMouseReleased);

    primaryStage.setScene(new Scene(new Group(button), 800, 600));
    primaryStage.show();
  }

  private void onAction(ActionEvent event) {
    event.consume();

    if (!wasDragged) {
      System.out.println("onAction");
    }
  }

  private void onMousePressed(MouseEvent event) {
    event.consume();
    origin = new Point2D(event.getX(), event.getY());

    System.out.println("onMousePressed");
  }

  private void onMouseDragged(MouseEvent event) {
    event.consume();
    wasDragged = true;

    Button source = (Button) event.getSource();
    source.setTranslateX(source.getTranslateX() + event.getX() - origin.getX());
    source.setTranslateY(source.getTranslateY() + event.getY() - origin.getY());
  }

  private void onMouseReleased(MouseEvent event) {
    event.consume();
    origin = null;
    wasDragged = false;

    System.out.println("onMouseReleased");
    System.out.println();
  }

}

不幸的是,我找不到保证onAction处理程序总是在onMouseReleased处理程序之前调用的文档,但是当我尝试使用它时,它在Java 8u202和JavaFX 11.0.2上都可以使用。