I was just doing random stuff with GUI and I came to this issue.When I press right arrow key, rectangle really moves on X axis, but distance moved is not constant.It's raising pretty fast and rectangle does after each press bigger moves.In my recent code line X=X+1
seemed to work pretty fine.Here's my code:
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Buffer extends JPanel implements KeyListener{
public static JFrame frame;
public int x;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x,0,20,20);
frame.addKeyListener(this);
}
public static void main(String args[]){
Buffer z=new Buffer();
frame=new JFrame();
frame.setSize(500,500);
frame.setVisible(true);
frame.setFocusable(true);
frame.add(z);
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
x=x+1;
repaint();
}
}
}
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.