I'm trying to make a pong game but my pong paddle isn't moving up properly for some reason.
When I hit the DOWN arrow key it moves down just fine. But when I hit the UP arrow key the whole paddle just get's longer upwards... If i resize the window the paddle returns to it's normal length at that position. If i press UP key it again continues to extend upwards.
I don't think its my code logic but something about clearing the previously drawn paddle... here's my code,
Code for Paddle:
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;
}
}
Code for Whole Game:
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);
}
}
Any help on this issue or general code advice would be appreciated.
See Question&Answers more detail:os