使用键盘适配器结束计时器?

Ending a timer using keyadapters?

所以,我正在创建这个显示蓝色球的反应时间游戏,一旦你看到那个蓝色球,你就按向上箭头键,在它变成蓝色后获得你的反应时间。但是,我在创建计时器时遇到了麻烦。我希望计时器在球实际变蓝后开始计时,并希望计时器在用户按下向上箭头后结束。'

Here's an image of what I want the game to look like before the ball turns blue

and this is what I want it to look like after it turns blue, with the reaction time

这是我的代码。截至目前,一切正常,只是我需要帮助的计时器部分。我想在球变蓝后立即创建一个计时器,并希望该计时器在用户按下向上箭头后结束,但我只是不知道如何...

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.Timer;


public class Game extends JPanel implements KeyListener
{

private JLabel start, main, time;
private ImageIcon constant, react;

final int width = 600;
final int height = 600;

private Timer replace;


private Random random;
private int randTime;

private long startTime;
private long stopTime;
private long reactionTime;

public Game()
{
  addKeyListener(this);
  setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

setPreferredSize(new Dimension(width, height));
setBackground(Color.black);

start = new JLabel("Click Up Arrow when you see a blue ball");
start.setForeground(Color.white);
start.setAlignmentX(Component.CENTER_ALIGNMENT);
add(start);
 
constant = new ImageIcon("constantCircle.png");
main = new JLabel(constant);
main.setAlignmentX(Component.CENTER_ALIGNMENT);


randomTime();
replace = new Timer(randTime, timeListener);
replace.setRepeats(false);
replace.start();

timeTracker();
reactionTime = stopTime - startTime;
time = new JLabel("" + reactionTime);

add(time);
add(main);

}


public void randomTime()
{
  random = new Random();
  int max = 8000;
  randTime = random.nextInt(max);

}


ActionListener timeListener = new ActionListener()
{
  public void actionPerformed (ActionEvent e)
  {
    react = new ImageIcon("reactCircle.png");
    main.setIcon(react);
  
  }
};

public void timeTracker()
{
 if (replace.isRunning())
 {
   startTime = System.currentTimeMillis();
 }

}

public void keyPressed (KeyEvent e)
{  
  int key = e.getKeyCode();

  if (key == KeyEvent.VK_SPACE)
  {
    stopTime = System.currentTimeMillis();      
  }

}

public void keyReleased(KeyEvent e)
{
}

public void keyTyped (KeyEvent e)
{
}

}

不需要计时器。定时器用于在指定的时间间隔生成事件。你不知道用户什么时候会做出反应,所以你不能使用计时器。

对于您的情况,您需要做的就是:

  1. 将“startTime”变量设置为设置蓝色球图标时的当前时间。

  2. 那么你需要在按下“向上”键时设置“stopTime”变量。这时你再计算你的“反应时间”。

问题是您的 KeyListener 不起作用,因为 KeyEvent 仅被分派到具有焦点的组件,而默认情况下 JPanel 没有焦点。

解决方案是使用 Key Bindings,而不是 KeyListener。即使面板没有焦点,也可以将键绑定配置为接收 KeyEvent。

阅读 How to Use Key Bindings 上的 Swing 教程部分了解更多信息。此站点上还有大量使用键绑定的示例。