How do I listen for mouse wheel presses?
Asked Answered
H

2

8

Is there any way to listen for mouse wheel presses (not moving the wheel, just pressing it)?

I have checked the MouseWheelListener API but there is nothing on mouse wheel presses, just wheel movings.

Husking answered 5/1, 2012 at 13:6 Comment(0)
B
10

Mouse wheel button is usually mouse button 2:

public void mouseClicked(MouseEvent evt) {

    if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
      System.out.println("middle" + (evt.getPoint()));
    }

 }

or even better:

SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
Buehler answered 5/1, 2012 at 13:8 Comment(1)
+1 for SwingUtilities.isMiddleMouseButton(MouseEvent). I have found this is inconsistent across platforms, and did not know about this method. Thanks!Phobia
P
1

Mouse wheel presses are reported through the MouseListener interface.

Use the mousePressed and mouseReleased events and check the MouseEvent.getButton() method to return the button number pressed or released.

You can also detect clicks with the mouseClicked event, but I have found that the built-in criteria for mouse clicks is too narrow. In this case, however, multiple mouse buttons could be clicked and you can use MouseEvent.getModifiers() to get a bitmask of the pressed buttons.

Phobia answered 5/1, 2012 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.