我正在尝试制作乒乓球游戏,但由于某种原因,我的乒乓球拍无法正常向上移动。
当我按下向下箭头键时,它向下移动就好了。但是当我按下向上箭头键时,整个桨向上变长了……如果我调整窗口大小,桨在那个位置返回到它的正常长度。如果我再次按下 UP 键,它会继续向上延伸。
我不认为这是我的代码逻辑,而是关于清除先前绘制的桨的一些东西......这是我的代码,
桨的代码:
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;
public class Paddle extends JPanel {
int x;
int y;
int width;
int height;
Paddle(){
this.x = 0;
this.y = 0;
this.height = 40;
this.width = 10;
}
Paddle(int x, int y, int width, int height){
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(x, y, width, height);
}
public void moveDown(){
this.y += 3;
repaint();
System.out.println("h: " + height + " x: " + x + " y: " + y + " getW: " + getWidth() + " getH: " + getHeight());
}
public void moveUp(){
this.y -= 3;
repaint();
System.out.println("h: " + height + " x: " + x + " y: " + y + " getW: " + getWidth() + " getH: " + getHeight());
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
整个游戏的代码:
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Pong extends JFrame {
Pong() {
final Paddle p1Paddle = new Paddle();
Paddle p2Paddle = new Paddle();
p1Paddle.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
//super.keyPressed(arg0);
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN:
p1Paddle.moveDown();
break;
case KeyEvent.VK_UP:
p1Paddle.moveUp();
break;
default:
System.out.println("please press up or down");
}
}
});
setLayout(new BorderLayout());
add(p1Paddle, BorderLayout.CENTER);
//only focused components can recieve key events...
p1Paddle.setFocusable(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new Pong();
frame.setTitle("Pong");
frame.setSize(650, 300);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
对此问题的任何帮助或一般代码建议将不胜感激。