如何用箭头键移动矩形? [英] 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)
这是我的Rectangle课:
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
}
}
这是主要内容:
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);
}
}
推荐答案
这里有很多问题:
问题是您的矩形图形是经过硬编码的,在这里可以证明:
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);
}
您需要使用x
变量而不是125
You need to use your x
variable instead of 125
为了接受按键事件,您的JPanel需要接受焦点,这可以通过以下几行来实现:
In order to accept key press events, your JPanel needs to accept focus, which can be achieved with the following lines:
setFocusable(true);
requestFocusInWindow();
您现在将收到键盘事件并更改您的x
值.不幸的是,这不会触发重新粉刷,因此您的盒子仍然不会移动.
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.
由于职责分配有些奇怪,因此您应该进一步细分您的课程.发生键事件时,您需要告诉JPanel repaint()
本身,更新内容会反映在屏幕上.
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.
这篇关于如何用箭头键移动矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!