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 to make these 2 rectangles collide?

+Pie Number of slices to send: Send
For the code below i managed to make these rectangles collide and bound at the Jpanel border, but why is that these rectangle do not bound each other when they collide, instead they overlap each other ?
I think there is a problem within my actionPerformed method. Please tell me why they overlap each other and how to overcome it.
Below is the code.Thank you.








+Pie Number of slices to send: Send
Welcome to the Ranch

It would be better not to extend JFrame, nor make display classes implement action listener. Give the paintComponent() method protected access, not public. Also flag it with the @Override annotation to verify you haven't made a tiny spelling error. I am afraid I am finding your variable names difficult to read, but I presume some mean the velocity you are moving your rectangles at.
Use the following idiom to add an action listener, which takes advantage of ActionListener being a functional interface, even though it isn't marked with that annotation:-If the syntax is unfamiliar, look in the Java™ Tutorials.
Repeatedly calculate the distance between the two rectangles and use that to change the direction; you won't get anything from Rectangle2D#intersects() until after they start to overlap. Beware of hard‑coding the width (450) (line 81/84): use some getWidth() method instead. Hard‑coding numbers is error‑prone: besides, the user may resize the display and make 450 incorrect.
Did you write your own Rectangle class or did you use java.awt.Rectangle? I would probably have used Rectangle2D, but that is a supertype of the java.awt class.
2
+Pie Number of slices to send: Send
The problem is that you have two fields rectanlgle, but in your paintComponent you use two different (local) rectangles. The field rectangles do not get changed, so that is why the rectangles that you see overlap and contimue their way.

So, in your paintComponent, just do:
+Pie Number of slices to send: Send
Thanks Piet Souris. Help me a lot.

reply
reply
This thread has been viewed 571 times.
Similar Threads
Why the blue and red rectangle exceed the JPanel border?
How do you animate current shapes using buttons in Java Applets?
How can I add an object on top of an existing filled squares JPanel so that it moves over it
Different Colour for different group of overlapping circles.
To make moving ball
More...

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