Skip to content
Advertisement

Ending a timer using keyadapters?

So, I am creating this reaction time game that shows a blue ball and once you see that blue ball, you press up arrow key to get your reaction time once it turned blue. However, I am having trouble in creating a timer. I want the timer to start once the ball actually turns blue and want that timer to end once the user presses up arrow.’

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

here is my code. As of right now, everything works fine its just the timer part I need help with. I want to create a timer as soon as the ball turns blue and want that timer to end once the user presses up arrow but I just dont know how…

JavaScript

Advertisement

Answer

There is no need for a Timer. A Timer is used to generate an event at a specified time interval. You don’t know when the user will react so you can’t use a Timer.

In your case all you need to do is:

  1. set your “startTime” variable to the current time when the blue ball icon is set.

  2. then you need to set the “stopTime” variable when the “Up” key is pressed. At this time you would then calculate your “reactionTime”.

The issue is that your KeyListener doesn’t work, because a KeyEvent is only dispatched to the component with focus and by default a JPanel doesn’t have focus.

The solution is to use Key Bindings, not a KeyListener. A Key Binding can be configured to receive the KeyEvent even when the panel doesn’t have focus.

Read the section from the Swing tutorial on How to Use Key Bindings for more information. There are also plenty of example on this site that use key bindings.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement