简体   繁体   English

如何用箭头键移动矩形?

[英]How to move a Rectangle with arrow keys?

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: 这是我的Rectangle类:

 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);
    }       
}

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 您需要使用x变量而不是125

In order to accept key press events, your JPanel needs to accept focus, which can be achieved with the following lines: 为了接受按键事件,您的JPanel需要接受焦点,这可以通过以下几行实现:

setFocusable(true);
requestFocusInWindow();

You will now receive keyboard events and alter your x value. 现在,您将收到键盘事件并更改x值。 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. 发生键事件时,您需要告诉JPanel repaint()本身以使更新反映在屏幕上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM