Reputation: 51
Can anybody tell me how I can stop the rectangles from going off the panel (screen) in my game? The rectangles move side by side with keystrokes.
Upvotes: 2
Views: 950
Reputation: 324118
Don't use a KeyListener. Swing was designed to be used with Key Bindings
.
See Motion With the Keyboard for working examples. The examples will also do boundary checking to make sure the component is contained within its parents bounds.
Upvotes: 2
Reputation: 24998
Here is what you should do :
1. Keep a track of (x,y)
coordinates of your rectangles.
2. Ensure that x + width
of your rectangle is not greater than width of the JPanel
for checking the collision with right edge
3. Ensure that x
is not less than 0 to check the collision left edge.
4. Ensure that y + height
is not greater than height of the JPanel
to check the collision with bottom edge
Can you guess what it will be for the top edge ?
Upvotes: 2