RHS   Allan   Game Techniques Exercises Exercise02


 

Exercise 02

Please use Textpad or another plain textoriented editor for othis exercise.
To fully understand the GUI aspects its a good idea not to let a GUI-builder (i.e. Netbeans) do all the tricks for you!
Its only for this exercise - later you're free to use whatever tool you like.

Question 1
Now we'll ad some action to the JFrame from Exercise01, question 5.
Add a panel with two buttons (labeled "Right" and "Down") to your main-frame. The listener for the buttons should be the frame itself. Note that if you use Netbeans it will create and add an anonymous sub-class of ActionListener to the buttons. The actionPerformed() method will just delegate the action to a special method in the frame (i.e. jButton1ActionPerformed()).
You should not do that!
Either you must change the code in Netbeans or use another editor (i.e. Textpad). Either way it should be the frame that is implementing the ActionListener interface!

Now add action to the buttons. When the right-button is clicked the ball's x-coordinate should be changed to the right, and when the left-button is clicked the x-coordinate should be changed to the left. After each change of the ball's coordinates it should be repainted.

Question 2
Add a Timer to the panel - let it fire an event 4 times every second. When the Timer fires an event the Ball's y-coordinate should be changed downwards.

Question 3 - Extra
Now change the actionPerformed() method so the ball can't leave the frame.

So if a button click would mean that the surface of the ball doesn't belong to the frames coordinates the click should be ignored.
And if the movement downwards caused by the Timer brings the ball out of the frame the direction should be shifted.
That is if the movement currently is downwards it should be changed so the Timer now moves the ball upwards.
And of course it the current direction is upwards it should be changed to downwards.


Maintained by: Allan Helboe Nielsen
Updated: 3 November, 2005 1:04