I initially had an answer about Key Bindings, but after a bit of testing, I found that they still had the same stuttering problem.
Do not rely on the OS repetition rate. It may be different for each platform, and the user can also configure it.
Instead, use a timer to schedule an event. You start the timer on the Raised key and stop the timer on keyReleased.
import java.awt.*; import java.awt.event.*; import java.net.*; import java.util.Map; import java.util.HashMap; import javax.imageio.ImageIO; import javax.swing.*; public class KeyboardAnimation implements ActionListener { private final static String PRESSED = "pressed "; private final static String RELEASED = "released "; private final static Point RELEASED_POINT = new Point(0, 0); private JComponent component; private Timer timer; private Map<String, Point> pressedKeys = new HashMap<String, Point>(); public KeyboardAnimation(JComponent component, int delay) { this.component = component; timer = new Timer(delay, this); timer.setInitialDelay( 0 ); } public void addAction(String keyStroke, int deltaX, int deltaY) {
This code has been tested on Windows, where the order of events is keyPressed, keyPressed, keyPressed ... keyReleased.
However, on Mac (or Unix), I think the order of events will be keyPressed, keyReleased, keyPressed, keyReleased ... So I'm not sure if this code will work better than your current code.
source share