如何在javafx中使用时间线进行双击?

tktrz96b  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(238)

这个问题在这里已经有答案了

如何在javafx中区分单击或双击表行(2个答案)
上个月关门了。
这是我到目前为止所做的,它工作得很好,但是当我双击时,双击事件被激发,而单击事件被激发,当我只单击时,单击当然被激发。

long currentMillis = System.currentTimeMillis();

addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {

  long currentClickedMillis = System.currentTimeMillis();
  long diffMillis = currentClickedMillis - currentMillis;
  currentMillis = currentClickedMillis;
  if (diffMillis > 500) {
    fireEvent(new FlightListEvents(FlightListEvents.FLIGHT_BUTTON_CLICKED, this.aircraft));
  } else {
    fireEvent(new FlightListEvents(FlightListEvents.FLIGHT_BUTTON_DOUBLE_CLICKED, this.aircraft));                   
  }
});

堆栈溢出的其他解决方案不起作用!他们只是计算点击次数,仍然有我现在的问题。

a7qyws3x

a7qyws3x1#

我曾经遇到过同样的问题,也找不到解决办法,所以我只好自己制定解决办法。
为此,我使用了javafx的 Timeline 这将使你能够在第一次点击时开始一条时间线,并且取决于你之后是否进行第二次点击,它将认为是一次点击或双击,但决不能同时进行两次点击。
以下是我的解决方案:

// initialize your timeline
final Timeline clickTimeline = new Timeline();
// minimum duration of a double click 500ms
Duration clickDuration = Duration.millis(500);
KeyFrame clickKeyFrame = new KeyFrame(clickDuration);
boolean isClickTimelinePlaying = false;
clickTimeline.getKeyFrames().add(clickKeyFrame);

addEventFilter(MouseEvent.MOUSE_CLICKED, e -> {
  if (isClickTimelinePlaying) {
    // when clicking the second time before the time line finishes
    isClickTimelinePlaying = false;
    fireEvent(new FlightListEvents(FlightListEvents.FLIGHT_BUTTON_DOUBLE_CLICKED, this.aircraft));
    clickTimeline.stop();
  } else {
    // when clicking for the first time
    isClickTimelinePlaying = true;
    // start the timeline
    clickTimeline.play();
  });
}

// if timeline finises without receiving a second click, consider it a single click
clickTimeline.setOnFinished(event -> {
  fireEvent(new FlightListEvents(FlightListEvents.FLIGHT_BUTTON_CLICKED, this.aircraft));
  isClickTimelinePlaying = false;
});

相关问题