I am trying to create a small program with Windowbuilder that simply paints a red rectangle (called car1) in a JPanel and move it around by pressing the arrow keys; to do th
This is a solution:
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
car1.move_left();
car1.repaint();
}
if (key == KeyEvent.VK_RIGHT) {
car1.move_right();
car1.repaint();
}
}
});
Where are the mistakes:
addKeyListener
: add key listener to frame, not to panelVK_KP_
: use VK_
prefix insteadkeyTyped
: use keyPressed
insteadNext step you will have to solve is removing the previous rectangles