如何在java中单击事件时检查是否按下了键

时间:2015-06-12 17:20:29

标签: java event-handling mouseevent keyboard-events

我想在按下按键时(不是按住Ctrl键,或按住Shift键或alt键)来捕获java中的Clicked事件,或者检查是否按键" A"按下键盘" D"按下。我怎么能这样做,比如方法isshiftdown?

4 个答案:

答案 0 :(得分:0)

像这样添加一个鼠标监听器:

component.addMouseListener(new MouseAdapter(){
  public void mousePressed(MouseEvent e){
    mouseDown = true;
  }
  public void mouseReleased(MouseEvent e){
    mouseDown = false;
  }
});

和关键听众:

component.addKeyListener(new KeyAdapter(){
  public void keyPressed(KeyEvent e){
    if(mouseDown){
      System.out.println("the key was pressed while the mouse is down.");
    }
  }
});

答案 1 :(得分:0)

不确定它是否是你想要的。你可以使用名为KeyEvent的java.awt.event包中的一些东西。

这是一个完整的例子:

https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/events/KeyEventDemoProject/src/events/KeyEventDemo.java

将其复制到您自己的IDE并运行

答案 2 :(得分:0)

我喜欢做的是使用布尔数组来存储当前按下的键,然后在需要时使用其他方法来访问它们。例如......

Boolean[] keys = new Boolean[256];
Boolean mousePressed = false;
...
keyPressed(MouseEvent e) {
    keys[e.getKeyCode()] = true;
}
...
keyReleased (MouseEvent e) {
    keys[e.getKeyCode()] = false;
}
....
mousePressed (MouseEvent e) { mousePressed=true; }

然后,只要你需要看到按键组合,只需引用数组并查看该键当前是否为真。它同样适用于鼠标和主要听众。

答案 3 :(得分:0)

你可以通过制作一个布尔数组来做到这一点,当按下键时,将键的布尔值设置为true,不按下时将其设置为false。

public boolean[] key = new boolean[68836];

不要问我为什么它是68836 ... 你的课看起来像这样:

public class keyHandler implements KeyListener, MouseListener{

int KeyCode = 0;
Main main;

    public KeyHandler(Main main){
        this.main = main;
    }
    public void keyPressed(KeyEvent e) {
        keyCode = e.getKeyCode();

        if (keyCode > 0 && keyCode < key.length) {
            main.key[keyCode] = true;
        }
    }
    public void keyReleased(KeyEvent e) {
        keyCode = e.getKeyCode();

        if (keyCode > 0 && keyCode < key.length) {
            main.key[keyCode] = false;
        }
    }
    public void mousePressed(MouseEvent e) {
        main.MouseButton = e.getButton();
        main.MousePressed true;
    }

    public void mouseReleased(MouseEvent e) {
        main.MouseButton = 0;
        main.MousePressed = false;
    }
}

接下来,您将拥有某种循环类,以便您定期检查布尔值:

public class Time extends Thread{
    Main main;
    public Time(Main main){
        this.main = main;
    }
    public void run(){
        while(true){
            main.update();// you would probably want some timing system here
        }
    }
}

然后在你的主要课程或其他东西:

public class Main {
//whatever you have here
public boolean[] key = new boolean[68836];
int MouseButton = 0;
boolean MousePressed = false;

    public Main(){
        Component c; //whatever you are using e.g JFrame
        //whatever you do to your component
        KeyHandler kh = new KeyHandler(this);
        c.addKeyListener(kh);
        c.addMouseListener(kh);
    }

    public void update(){
        if(key[KeyEvent.VK_A] && key[KeyEvent.VK_D){
            //both keys are pressed
        }
    }
}