How to move a Rectangle with arrow keys?

不问归期 提交于 2019-12-25 02:57:07

问题


I have a frame which as a rectangle in it. I want to know how can I move the rectangle in if I clicked the arrow keys. I searched, and find few examples but nothing worked (weird, as it should be a simple thing to do)

Here is my Rectangle class:

 public class PlayerOne implements KeyListener {

    int x,y;
    public PlayerOne(JPanel panel){
        this.x = panel.getWidth()/2;
        this.y = panel.getHeight()/2;
    }

    public void paint(Graphics g){
        g.setColor(Color.RED);
        g.fillRect(125, 480, 60, 10);
    }

    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub
        int keyCode = arg0.getKeyCode();
        if(keyCode == arg0.VK_KP_RIGHT){
            this.x+=5;
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub          
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub          
    }    
}

This is the main:

public class PingPong extends JPanel {

    private static final long serialVersionUID = -4170574729049260633L;

    //Initialize
    Table table = new Table();
    PlayerOne po = new PlayerOne(this);

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        table.paint(g);
        po.repaint(g);
    }

    public static void main(String[] args){
        JFrame frame = new JFrame();            
        frame.setTitle("Pong");
        frame.setSize(326, 533);
        frame.add(new PingPong()).setBackground(Color.DARK_GRAY);
        frame.getContentPane().setBackground(Color.DARK_GRAY);
        frame.setVisible(true);
    }       
}

回答1:


There's a bunch of problems here:

The problem is that your rectangle drawing is hardcoded, evidenced here:

public void paint(Graphics g){
    g.setColor(Color.RED);
    g.fillRect(125, 480, 60, 10);
}

You need to use your x variable instead of 125

In order to accept key press events, your JPanel needs to accept focus, which can be achieved with the following lines:

setFocusable(true);
requestFocusInWindow();

You will now receive keyboard events and alter your x value. Unfortunately this won't trigger a repaint so your box still won't move.

You should really break apart your classes a bit more as your allocation of responsibilities is a bit strange. When a key event occurs, you need to tell your JPanel to repaint() itself to updates are reflected on screen.



来源:https://stackoverflow.com/questions/30237571/how-to-move-a-rectangle-with-arrow-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!