Win a copy of Raising Young Coders: A Parent’s Guide to Teaching Programming at Home this week in the General Computing forum!
Forums Login/signup

How can I add an object on top of an existing filled squares JPanel so that it moves over it

+Pie Number of slices to send: Send

Here is my code but I can't understand why it would not add the moving oval on top of the existing filled squares panel
Please help






1
+Pie Number of slices to send: Send
hi Ion,

there are some mistakes in your code, and they are a bit complicated to explain. I will have a go:

1) your Game panel overrides the 'paint' method. This is not something you should do. A normal paint does three things: it calls 'paintComponent', where you draw your user graphics (as you do in the GamObject class). Second, it calls 'paintBorder' to draw a Border if it is there, and lastly, it calls 'paintChildren', drawing any component that has been added (here it is an instance of GameObject).

As you see, in yout 'paint' method there is no 'paintChildren', so the GameObject is in principal not drawn. That you see it nevertheless is because the Timer makes it repaint constantly, meaning it is visible anyway.

So, override just the 'paintComponent' in Game, as you do in GameObject.

2) but, as you write, you see no GameObject at all! That is because its size is 0. Although you do: r.setSize(...), that does not work. Use: r.setPreferredSizr(new Dimension(500, 500) instead.

3) but now the checkersboard dissapears! That is because the GameObject panel has a background color, that almost completely hides the checkerboard. So, give the GameObject panel a transparent background, like 'r.setBackground(new Color(0, 0, 0, 0);'

Then it is still not perfect (the checkerboard gets shifted a little. I suspect what causes that, but I have no solution yet), but you see what you had in mind.

There are simpler ways to achieve your goal, though.

reply
reply
This thread has been viewed 265 times.
Similar Threads
JFrame - multithreading
Want confirmation that I am doing everything right
From keyboard movement to mouse movement.
Checkerboard w/ 64 squares
More...

All times above are in ranch (not your local) time.
The current ranch time is
Jun 27, 2025 08:52:30.