java 检测由摆动中的单击生成的 MouseEvent 上的 Shift 修饰符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5517674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting Shift modifiers on MouseEvent generated from click in swing
提问by Heisenbug
I'm handling some MouseEvent in a GUI application using Java Swing.
我正在使用 Java Swing 在 GUI 应用程序中处理一些 MouseEvent。
Since now i was analyzing mouse events inside mousePressed method, only to determine if a left or right click happened.
因为现在我正在分析 mousePressed 方法中的鼠标事件,只是为了确定是否发生了左键或右键单击。
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:
现在我的应用程序变得越来越复杂,我还需要检查鼠标左键单击时是否按下了 Shift 按钮。我想做这样的事情:
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.
现在这不起作用。特别是如果我在按住 SHIFT 的同时单击左按钮 isShiftDown 返回 true(正确。我期待那样),但现在似乎修饰符也发生了变化并且与 BUTTON1_DOWN_MASK 的比较失败。
me.getModifiers == InputEvent.BUTTON1_DOWN_MASK //failed..modifiers are changed
What am I doing wrong? How can I fix my code?
我究竟做错了什么?我该如何修复我的代码?
回答by Ernest Friedman-Hill
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:
请注意,该方法称为 getModifier_s_(),带有一个“s”,因为它可以返回多个修饰符,使用按位“或”组合。从技术上讲,使用“==”是不正确的:您应该使用按位“&”,如下所示:
if ((me.getModifiers() & InputEvent.BUTTON1_DOWN_MASK) != 0) ...
then you'll respond to that one modifier, even if others are present.
那么你会回应那个修改器,即使其他修改器在场。
回答by John Ganci
You should use
你应该使用
if ((me.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) != 0)
or
或者
if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0)