繁体   English   中英

同时使用MouseListener和KeyListener

[英]MouseListener and KeyListener used at the same time

如何同时使用MouseListener和KeyListener?

例如,如何做这样的事情

public void keyPressed( KeyEvent e){
// If the mouse button is clicked while any key is held down, print the key
}

使用布尔值表示是否按住了鼠标按钮,然后在MouseListener中更新该变量。

boolean buttonDown = false;

public class ExampleListener implements MouseListener {
    public void mousePressed(MouseEvent e) {
        buttonDown = true;
    }

    public void mouseReleased(MouseEvent e) {
        buttonDown = false;
    }

    //Other implemented methods unimportant to this post... 
}

然后,在KeyListener类中,只需测试buttonDown变量。

尝试创建一个布尔值isKeyPressed keyPressed中将其设置为true,在keyReleased中将其设置为false。 然后,当单击鼠标时,首先检查isKeyPressed是否为true。

您可以尝试检查KeyEvent修饰符的状态,例如...

addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        int mods = e.getModifiers();
        System.out.println(mods);
        if ((mods & KeyEvent.BUTTON1_MASK) != 0) {
            System.out.println("Button1 down");
        }
    }
});

我还应该指出,你可以...

int ext = e.getModifiersEx();
if ((ext & KeyEvent.BUTTON1_DOWN_MASK) != 0) {
    System.out.println("Button1_down_mask");
}

正如我刚刚发现的那样,它会为其他鼠标按钮产生结果...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM