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



我想在按下键(不是ctrl,shift或alt)时在java中捕获Clicked事件,或者检查键"A"是否按下了druing键"D"。我怎么能做到这一点,类似方法的东西是移位?

添加如下所示的鼠标侦听器:

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.");
    }
  }
});

您可以通过制作布尔值数组来做到这一点,当按下键时,将该键的布尔值设置为 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
        }
    }
}

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

下面是一个完整的示例:

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

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

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

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; }

然后,每当您需要查看它时,都会按下组合键,只需引用数组并查看该键当前是否为真。它同样适用于鼠标和关键侦听器。

相关内容

  • 没有找到相关文章

最新更新