本文介绍了检测MouseEvent上的Shift修改器是否因为单击摇摆而生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java Swing在GUI应用程序中处理一些MouseEvent。

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

从现在开始我在mousePressed方法中分析鼠标事件,只是为了确定
a左或右点击发生。

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

我的代码是:

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

现在我的申请变得越来越复杂了我还需要检查鼠标左键单击时是否按下了Shift键。
我想这样做:

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
    }

现在这不起作用。特别是如果我按住SHIFT时单击左按钮isShiftDown返回true(rigth。我当时正在等待),但现在似乎修改器也被更改并且与BUTTON1_DOWN_MASK的比较失败。

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?

推荐答案

请注意,该方法名为getModifier_s_(),带有s,因为它可以返回多个修饰符,使用按位或组合。使用==在技术上永远不正确:你应该使用按位&,如下所示:

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.

这篇关于检测MouseEvent上的Shift修改器是否因为单击摇摆而生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:17