gpt4 book ai didi

java - 同时按下多个键后释放键时不会触发 KeyListener

转载 作者:行者123 更新时间:2023-11-29 05:49:55 25 4
gpt4 key购买 nike

我正在编写一个使用 key 监听器的小型应用程序。当一个特定的键被按下时,计时器启动,当该键被释放时,计时器停止。

现在这只有在同时按下一个键时才能完美运行。当我同时按下 3 个键时,所有三个计时器都可以正常启动。我遇到的问题是键一个接一个地被释放。我尝试使用 InputMap 和 ActionMap,但遇到了另一个问题。

  import java.awt.event.*; 
import javax.swing.*;
public class KeyTest extends JFrame implements KeyListener{
private static final int UP_TIMER_DELAY = 200;
// a timer for button "Z"
private Timer upTimer;
// a timer for button "X"
private Timer upTimer2;

public static void main(String[] args)
{
new KeyTest();
}

public KeyTest()
{
this.addKeyListener(this);
this.setSize(800,600); this.setVisible(true);
}


public void keyPressed(KeyEvent e)
{
//When Z is pressed
if(e.getKeyCode()==90)
{
if (upTimer != null && upTimer.isRunning()) {
return;
}
System.out.println("Button_Z is pressed");

upTimer = new Timer(UP_TIMER_DELAY,
new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

}
});
//Starting the timer for Button "Z" if pressed
upTimer.start();
}
else {
if (upTimer != null && upTimer.isRunning()) {
upTimer.stop();
upTimer = null;
}
}
//When X is pressed
if(e.getKeyCode()==88)
{
if (upTimer2 != null && upTimer2.isRunning()) {
return;
}
System.out.println("Button_X is pressed");

upTimer2 = new Timer(UP_TIMER_DELAY,
new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

}
});
upTimer2.start();
}
else {
if (upTimer2 != null && upTimer2.isRunning()) {
upTimer2.stop();
upTimer2 = null;
}
}
}

public void keyReleased(KeyEvent e)
{
//When Z is released
if(e.getKeyCode()==90)
{

if (upTimer != null && upTimer.isRunning()) {
upTimer.stop();
upTimer = null;
System.out.println("Button_Z is released");
}
}

//When X is realeased
else if(e.getKeyCode()==88)
{

if (upTimer2 != null && upTimer2.isRunning()) {
upTimer2.stop();
upTimer2 = null;
System.out.println("Button_X is released");
}
}
}

public void keyTyped(KeyEvent e)
{
// Do stuff.
}
}

最佳答案

当您自己按下另一个键时,您将取消计时器。

java.awt.event.KeyEvent[KEY_PRESSED,keyCode=90
Button_Z is pressed
Canceling Button_X timer
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=90
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=90
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=88
Canceling Button_Z timer
Button_X is pressed
java.awt.event.KeyEvent[KEY_RELEASED,keyCode=88
Button_X is released
java.awt.event.KeyEvent[KEY_RELEASED,keyCode=90 // but timer already canceled

关于java - 同时按下多个键后释放键时不会触发 KeyListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14338052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com