The Bouncing Ball Problem (Independent Threads)
Contents Problem Description A Single-Threading Solution A Multithreading Solution New Requirement: Bouncing an Image
I. Problem Description Develop a GUI program that animates a bouncing ball by continually moving the ball 1,000 times, each time 1 pixel in both x and y directions As soon as you click the Start button, the program launches a new ball from the upper- left corner of the screen and the ball begins bouncing (see the next slide) The delay between two moves is 3 ms
II. A Single-Threading Solution The Main Class Developing the View Adding Listeners to the Buttons The Shortcoming of This Solution
1. The Main Class
2. Developing the View
2.1. Add ballPanel to CENTER
2.2. Add buttonPanel to SOUTH
3. Adding Listeners to the Buttons 3.1. Adding Listener to the Close Button 3.2. Adding Listener to the Start Button
3.1. Adding Listener to the Close Button
3.2. Adding Listener to the Start Button 3.2.1. Bouncing a Ball 3.2.2. Taking Care of Multiple Balls
3.2.1. Bouncing a Ball
Make BallPanel as a Separate Class
Develop the Ball Class
Refactor the Position & Gradient Classes
Develop bounceBall()
Move the Ball
Sleep for 3 ms
Fit the Ball to the Panel
3.2.3. Bouncing Multiple Balls
4. The Shortcoming of This Solution The bouncing of a ball completely takes over the application We cannot interact with the program until the ball has finished bouncing
III. A Mutithreading Solution A simple procedure for running a task in a separate thread: Place the code for the task into the run method of a class that implements the Runnable interface public interface Runnable { void run(); } … class MyRunnable implements Runnable { public void run() { task code } }
Construct an object of your class: Runnable r = new MyRunnable(); Construct a Thread object from the Runnable: Thread t = new Thread(r); Start the thread: t.start();
III. A Mutithreading Solution Run the bouncing code in a separate thread
Execute the application and click Start button many times to get ConcurrentModificationException
Replace paint() by repaint()
Let the Balls Run Forever
IV. New Requirement: Bouncing an Image
Solution Look for the place where we can replace the ball by the image
Modify the listener of the Start Button
Modify bounceBall() by introducing an inheritance structure The main difference between BlackBall and ImageBall is show()
Execute the application to make sure that BlackBall works
Reference Core Java, Volume I – Fundamentals, Eighth Edition, Chapter 14. Cay S. Horstmann and Gary Cornell. Prentice Hall, 2008