1

I experimented with java.awt.event.MouseEvent and mouse buttons and modifier keys. Finally I came to a point, where I was confused by its behavior.

Normally I use SwingUtilities.isLeftMouseButton(...) etc. to detect, which mouse button is pressed and <MouseEvent>.isControlDown() etc. to detect, which modifier key is pressed.

But if I press the middle mouse button, the <MouseEvent>.isAltDown()-method seems to be always true, no matter the Alt-key is pressed or not (by the way same for right mouse button and meta key).

It seems some keys on keyboard share the same event flags as some mouse buttons. How to fetch the middle mouse button in java? seems to confirm my assumption.

So my question: Is there a way to detect which mouse button is pressed and which modifiers are really pressed? Or is it better to use only Ctrl and Shift modifier keys for conditional mouse events?

OS: Windows 8, java version "1.7.0_09"

Thank you in advance

Community
  • 1
  • 1
Michael Dietrich
  • 451
  • 1
  • 5
  • 17

1 Answers1

1

In regards to your issue with the Middle mouse button... http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6495530, it would appear that Sun/Oracle has known about this issue since 2006...

For other cases (at least simple ones) I do the following.

@Override
public void mouseClicked(MouseEvent e) {
     if (e.getClickCount() == 1 && e.getButton() == MouseEvent.BUTTON2){
         //Do some stuff...
         if (e.isControlDown()) {
             //Do something if control is down
         }else{
             //Something different if it is not down.
         }
     }
}

There is a similar helper for alt (which does not work with the middle button, its always true), shift and meta (is that the OS X key?).

I have noticed odd behavior if you want to handle double clicks, and single clicks separately as Java seems to honor a double click, but handles the single click as well.

Justin Smith
  • 413
  • 6
  • 12