【发布时间】:2021-08-12 19:13:16
【问题描述】:
所以,我正在创建这个显示一个蓝色球的反应时间游戏,一旦你看到那个蓝色球,你按下向上箭头键来获取你的反应时间,一旦它变成蓝色。但是,我在创建计时器时遇到了麻烦。我希望计时器在球真正变成蓝色时启动,并希望在用户按下向上箭头后计时器结束。'
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)
{
}
}
【问题讨论】:
标签: java swing timer keyboard jpanel