在java中启动计时器并使用keyadapter结束该计时器

在java中启动计时器并使用keyadapter结束该计时器,java,timer,keyboard,jframe,jpanel,Java,Timer,Keyboard,Jframe,Jpanel,在我的游戏中,我试图记录用户的反应时间。在我的比赛中,我先有一个红色的圆圈,然后变成蓝色。一旦球变成蓝色,我希望用户按下空格键,我希望在球变成蓝色后返回他们的反应时间。 下面是一个图像示例: 这是我的程序代码(我没有接触过keyPressed、KeyRelease或keyTyped方法,因为我不清楚如何执行它们。我想在按下键后停止计时器,但我不确定如何执行): public class Game extends JPanel implements KeyListener { private

在我的游戏中,我试图记录用户的反应时间。在我的比赛中,我先有一个红色的圆圈,然后变成蓝色。一旦球变成蓝色,我希望用户按下空格键,我希望在球变成蓝色后返回他们的反应时间。 下面是一个图像示例:

这是我的程序代码(我没有接触过keyPressed、KeyRelease或keyTyped方法,因为我不清楚如何执行它们。我想在按下键后停止计时器,但我不确定如何执行):

public class Game extends JPanel implements KeyListener
{

private JLabel start, main, timeTracker;
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()
{
  startTime = System.currentTimeMillis();
  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();

stopTime = System.currentTimeMillis();
reactionTime = stopTime - startTime;

timeTracker = new JLabel("Reaction is : " + reactionTime + "Ms");

add(timeTracker);
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 keyPressed (KeyEvent e)
{  
}

public void keyReleased(KeyEvent e)
{
}

public void keyTyped (KeyEvent e)
{
}