8

I'm handling some MouseEvent in a GUI application using Java Swing.

Since now i was analyzing mouse events inside mousePressed method, only to determine if a left or right click happened.

My code was:

public void mousePressed(MouseEvent me) {
    if (me.getModifiers == InputEvent.BUTTON1_DOWN_MASK){
     //left click
    }else if (me.getModifiers == InputEvent.BUTTON3_DOWN_MASK){
     //right click
     }

Now my application is becoming more complicated and I need also to check if Shift button was pressed while mouse was left clicking. I would like to do something like this:

public void mousePressed(MouseEvent me) {
    if (me.getModifiers == InputEvent.BUTTON1_DOWN_MASK && me.isShiftDown()){
     //left click
    }

Now this doesn't work. In particular if I click the left button while holding SHIFT isShiftDown returns true (rigth. i was expecting that), but now seems that modifiers are also changed and the comparison with BUTTON1_DOWN_MASK fails.

me.getModifiers == InputEvent.BUTTON1_DOWN_MASK //failed..modifiers are changed

What am I doing wrong? How can I fix my code?

Heisenbug
  • 38,762
  • 28
  • 132
  • 190

2 Answers2

12

Note that the method is called getModifier_s_(), with an "s", because it can return more than one modifier, combined using bitwise "or". It's technically never correct to use "==": you should use bitwise "&", like this:

if ((me.getModifiers() & InputEvent.BUTTON1_DOWN_MASK) != 0) ...

then you'll respond to that one modifier, even if others are present.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • you are right. Anyway your code (me.getModifiers() & InputEvent.BUTTON1_DOWN_MASK) doesn't return a boolean – Heisenbug Apr 01 '11 at 19:19
  • sorry. I'm a bit confused. Seems to work exactly in the opposite way: (me.getModifiers() & InputEvent.BUTTON1_DOWN_MASK) == 0 . Anyway..you got the point. thanks – Heisenbug Apr 01 '11 at 19:29
1

You should use

if ((me.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) != 0)

or

if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0)
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
John Ganci
  • 11
  • 1