Java – detects the shift modifier on mouseevent, which is generated by clicking from swing

I am using java swing to process some mouseevents in GUI applications

From now on, I analyze mouse events in the mousePressed method just to determine whether a left or right button has occurred

My code is:

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 that my application is becoming more and more complex, I also need to check whether the shift key is pressed when I click with the left mouse button I want to do something like this:

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

It doesn't work now Especially if I click the left button while holding down shift, isshiftdown returns true (right. What I expect is), but now it seems that the modifier has also been changed and is consistent with buton1_ DOWN_ Comparison of mask failed

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

What on earth did I do wrong? How can I fix my code?

Solution

Note that this method is called getmodifier_ s_ (), with's' because it can return multiple modifiers, using a bitwise or combination Technically, using "= =" is never correct: you should use bitwise "&", as follows:

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

Then you will respond to that modifier, even if other modifiers exist

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>