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.
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.
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:
I hate signatures!
posted 1 month ago
Thanks Piet Souris. Help me a lot.
WARNING! Do not activate jet boots indoors or you will see a tiny ad: