Rox
Rox

Reputation: 2917

How do I listen for mouse wheel presses?

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.

Upvotes: 8

Views: 3272

Answers (2)

Erick Robertson
Erick Robertson

Reputation: 33068

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.

Upvotes: 1

Wojciech Owczarczyk
Wojciech Owczarczyk

Reputation: 5735

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)

Upvotes: 10

Related Questions