Hey guys, I’m pretty much new to the Java Graphics part, and I have a couple questions as well.
Anyway, I was trying create a Pong game , and I’m already having some trouble with the ball moving part.
I don’t understand why isn’t the ball moving at all, all it does is flicker in the same place.
I usually extend JComponent in a class, and draw everything inside the paintComponent() method, so I just wanted to try something new I read, but yeah I just cant figure out what am I doing wrong ???
public class GUI {
JFrame frame;
Ball ball = new Ball();
GamePanel gamepanel = new GamePanel();
BallEngine engine = new BallEngine(gamepanel);
public GUI() {
frame = new JFrame("Pong");
frame.add(gamepanel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void execute() {
frame.setVisible(true);
engine.start();
}
public static void main(String[] args) {
GUI gui = new GUI();
gui.execute();
}
}
public class GamePanel extends JPanel {
private static final long serialVersionUID = 1L;
Ball ball = new Ball();
Paddle paddle = new Paddle();
public void paintComponent(Graphics g) {
super.paintComponent(g);
ball.paintBall(g);
paddle.paintPaddle(g);
}
public void update() {
ball.moveBall();
repaint();
}
}
public class Ball extends JLabel {
private static final long serialVersionUID = 1L;
int x = 150;
int y = 150;
int xVelocity = 1;
int yVelocity = 1;
public void paintBall(Graphics g) {
g.fillOval(x, y, 25, 25);
}
public void moveBall() {
if (x >= (getWidth() - 50) || x <= 0) {
xVelocity = -xVelocity;
}
if (y >= getHeight() - 50 || y <= 0)
yVelocity = -yVelocity;
x += xVelocity;
y += yVelocity;
}
}
public class BallEngine extends Thread {
GamePanel gamepanel = new GamePanel();
public BallEngine(GamePanel gamepanel) {
this.gamepanel = gamepanel;
}
@Override
public void run() {
while (true) {
try {
gamepanel.update();
} catch (Exception e) {
}
}
}
}