我正在编写一个使用键侦听器的小应用程序。当按下特定键时,启动计时器,并且当该键被释放时,计时器停止。
现在只有在按下一个键时才能完美地工作。当我同时按下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.
}
}
答案 0 :(得分:3)
当你自己按下另一把钥匙时取消计时器。
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