DarkHark
DarkHark

Reputation: 683

JavaFX WebView ScrollEvent listener zooms in and scrolls. Only want it to zoom in

I've been looking around to see if anyone has had this issue, but most of the issues seem unrelated. I have a JavaFX WebView inside of a scrollpane. I'm attempting to make it so when you hold ctrl + scrollwheel, it will zoom in and out accordingly.

The code does zoom in and out, but incorrectly. When I hold ctrl + scroll wheel, it both scrolls and zooms in or out.

Here is the relevant part of my code:

// Allow for dynamic zooming based on scrollwheel
  webview.addEventHandler(ScrollEvent.SCROLL, (ScrollEvent e) -> {
     System.out.println("Zoom in or out based on scroll bar");
     double deltaY = e.getDeltaY();
     System.out.println(deltaY + "    " + e.isControlDown());
     if(e.isControlDown() && deltaY > 0) {
        webview.setZoom(webview.getZoom() * 1.1);
     } else if(e.isControlDown() && deltaY < 0) {
        webview.setZoom(webview.getZoom() / 1.1);
     }
  });

I left the printout statements in to help with possible troubleshooting. Thank you ahead of time.

EDIT

I should probably include that I placed the WebView in the ScrollPane like so:

scrollpane.setContent(webview);

Upvotes: 2

Views: 550

Answers (1)

DarkHark
DarkHark

Reputation: 683

As @Slaw commented in my question, all I had to do was consume the event inside of my if statements and change the event processor from handler to a filter as shown below:

webview.addEventFilter(ScrollEvent.SCROLL, (ScrollEvent e) -> {
     double deltaY = e.getDeltaY();
     if(e.isControlDown() && deltaY > 0) {
        webview.setZoom(webview.getZoom() * 1.1);
        e.consume();
     } else if(e.isControlDown() && deltaY < 0) {
        webview.setZoom(webview.getZoom() / 1.1);
        e.consume();
     }
  });

Upvotes: 4

Related Questions