Remove the following line from public void paintComponent(Graphics g)
frame.addKeyListener(this);
and add the following line to public static void main(String args[])
frame.addKeyListener(z);
The problem was that after every repaint();
through the keyPressed
method, the paintComponent
method added a new KeyListener
to your frame.
But if you have several KeyListeners
, every Listener will invoke the keyPressed
method for the same event. So if you have 5 Listeners and you press the right arrow once, the keyPressed
method is invoked five times and x is incremented by five.
That meant that the rectangle moved with every hit of the right arrow a bit faster.