how to move an object in a JPanel using the arrow keys

前端 未结 2 1402
独厮守ぢ
独厮守ぢ 2021-01-17 03:29

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

2条回答
  •  -上瘾入骨i
    2021-01-17 04:17

    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:

    1. addKeyListener: add key listener to frame, not to panel
    2. VK_KP_: use VK_ prefix instead
    3. keyTyped: use keyPressed instead

    Next step you will have to solve is removing the previous rectangles

提交回复
热议问题