I have a class calledActivity
which extends JPanel
My problem is that I want the Activity
to run the game loop (update its fields and GUI and etc) every 1000ms, but to always be checking for (in order to respond to) key presses.
private final BitSet keys = new BitSet(256);
...
public void keyPressed(final KeyEvent e) {
keys.set(e.getKeyCode());
}
public void keyReleased(final KeyEvent e) {
keys.clear(e.getKeyCode());
}
...
public void actionPerformed(ActionEvent e) {
processKeys(); // Checks keys
processData(); // Main game loop
repaint(); // Draws game components
}
Presently, the class stores key presses in a BitSet
and every 1000ms, actionPerformed()
looks at the pressed keys (like moving player position to the right of right arrow is pressed), handles main game loop stuff (like ending the game if a boundary is hit), and repaints the screen, in that order.
The issue is that I have to press a key right before the timer fires in order for it to be detected, since otherwise it'll be deleted from the BitSet
by the time processKeys()
is called. I still want the game loop to run every 1000ms however.
I've considered either
- Creating 2 simultaneous timers -- 1000ms for the game loop, 1ms for key press analysis
- Setting the timer I have to 1ms, and using a class field to track timer fires. Check key presses every fire, and only run game loop/repaint when
fires % 1000 == 0
I am not sure if #1 creates performance issues or leads to timer discrepancies, and I am pretty sure #2 is unreliable since when I've tried it, often the field never hit 1000 or 2000 or etc exactly.
What is the solution?