2

This is basically the same question as this one but with JavaFX instead of java swing:

I want to know if a scroll event is generated by the trackpad or a mouse in JavaFX.

Community
  • 1
  • 1
lolero
  • 1,253
  • 2
  • 10
  • 18

1 Answers1

1

According to a documentation on ScrollEvent there is a subtle difference in handling scroll events from mouse and trackpad.

When the scrolling is produced by a touch gesture (such as dragging a finger over a touch screen), it is surrounded by the SCROLL_STARTED and SCROLL_FINISHED events.

Having that in mind you can track SCROLL_STARTED and SCROLL_FINISHED events and modify your SCROLL_EVENT handler in between these two boundaries. However the trackpad can send SCROLL_EVENTs after SCROLL_FINISHED being sent (scrolling inertia) so you can check out the event.isInertia() method to filter these events.

Due to a probable bug in JavaFX in rare cases SCROLL_EVENTs may occur after SCROLL_FINISHED with event.isInertia() == false (if you scroll on a trackpad very quickly many many times). The possible workaround is to track the timestamp of the last SCROLL_FINISHED event and to ignore these "ghost" events within short time period after that timestamp.

Example code:

long lastFinishedScrollingTime;
boolean trackpadScrolling;

node.setOnScroll(event -> {
    long timeDiff = System.currentTimeMillis() - lastFinishedScrollingTime;
    boolean ghostEvent = timeDiff < 1000; // I saw 500-700ms ghost events
    if (trackpadScrolling || event.isInertia() || ghostEvent) {
        // trackpad scrolling
    } else {
        // mouse scrolling
    }
});

node.setOnScrollStarted(event -> {
    trackpadScrolling = true;
});

node.setOnScrollFinished(event -> {
    trackpadScrolling = false;
    lastFinishedScrollingTime = System.currentTimeMillis();
});
SpaceCore186
  • 586
  • 1
  • 8
  • 22
Max
  • 11
  • 1
  • I have just tried your code and unfortunately it does not seem to work. Apparently the ghost even might be at fault. Using your code, my track pad is never detect, only mouse scroll and only significant mouse scroll. It is strange that JavaFX does not provide an easy way to detect the track pad... – Mackovich Sep 28 '18 at 07:56