I have seen a lot of questions that look like mine, and I have looked through all the answers, but I can't seem to find the answer I need.
I have a Paddle
class and a Ball
class for a game I am making.
In the Ball class, I have a paint method that draws and moves the ball. And in my Paddle class, I have a paint method that draws and moves the paddle. In my main class, I have a JFrame.
I would like to add my ball and paddle class to my JFrame, but the JFrame only displays the class that has been added last. I have tried adding my classes to a JPanel and then the JPanel to the JFrame, but that doesn't work either.
The code shown bellow has no errors (I may have made a typo) but simply only displays the paddle on the JFrame. (It is vice versa when I add the ball to the frame after I add the paddle to the frame). I would really appreciate any answers!
public class game {
JFrame frame = new JFrame();
//set size and visibility and all the other things
Ball ball = new Ball();
frame.add(ball);
Paddle paddle = new Paddle();
frame.add(paddle);
//repeats code underneath every 10 milliseconds using swing timer
ball.revalidate();
ball.repaint();
paddle.revalidate();
paddle.repaint();
}
My paint method in my ball class looks like this:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(ballx, bally, balldiamter, balldiamter);
}
My paint method in my paddle class looks like this:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(paddlex, paddley, paddleLength, paddleWidth);
}