简体   繁体   English

同时使用MouseListener和KeyListener

[英]MouseListener and KeyListener used at the same time

How do I use MouseListener and KeyListener at the same time? 如何同时使用MouseListener和KeyListener?

For example, how to do something like this 例如,如何做这样的事情

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

Use a boolean value for whether a mouse button is held down, and then update that variable in a MouseListener. 使用布尔值表示是否按住了鼠标按钮,然后在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... 
}

Then, in your KeyListener class, just test the buttonDown variable. 然后,在KeyListener类中,只需测试buttonDown变量。

Try creating a boolean isKeyPressed . 尝试创建一个布尔值isKeyPressed In keyPressed , set it to true and in keyReleased set it to false. keyPressed中将其设置为true,在keyReleased中将其设置为false。 Then, when the mouse is clicked, first check if isKeyPressed is true. 然后,当单击鼠标时,首先检查isKeyPressed是否为true。

You could try checking the state of the KeyEvent modifiers, for example... 您可以尝试检查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");
        }
    }
});

I should also point out, you can do... 我还应该指出,你可以...

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

Which, as I've just discovered, produces results for other mouse buttons... 正如我刚刚发现的那样,它会为其他鼠标按钮产生结果...

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

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