Download presentation
Presentation is loading. Please wait.
1
The Bouncing Ball Problem (Independent Threads)
2
Contents Problem Description A Single-Threading Solution
A Multithreading Solution New Requirement: Bouncing an Image
3
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
5
II. A Single-Threading Solution
The Main Class Developing the View Adding Listeners to the Buttons The Shortcoming of This Solution
6
1. The Main Class
7
2. Developing the View
8
2.1. Add ballPanel to CENTER
9
2.2. Add buttonPanel to SOUTH
10
3. Adding Listeners to the Buttons
3.1. Adding Listener to the Close Button 3.2. Adding Listener to the Start Button
11
3.1. Adding Listener to the Close Button
12
3.2. Adding Listener to the Start Button
Bouncing a Ball Taking Care of Multiple Balls
13
Bouncing a Ball
14
Make BallPanel as a Separate Class
15
Develop the Ball Class
18
Refactor the Position & Gradient Classes
19
Develop bounceBall()
21
Move the Ball
24
Sleep for 3 ms
25
Fit the Ball to the Panel
29
3.2.3. Bouncing Multiple Balls
30
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
31
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 } }
32
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();
33
III. A Mutithreading Solution
Run the bouncing code in a separate thread
34
Execute the application and click Start button many times to get ConcurrentModificationException
35
Replace paint() by repaint()
36
Let the Balls Run Forever
37
IV. New Requirement: Bouncing an Image
38
Solution Look for the place where we can replace the ball by the image
39
Modify the listener of the Start Button
40
Modify bounceBall() by introducing an inheritance structure
The main difference between BlackBall and ImageBall is show()
42
Execute the application to make sure that BlackBall works
44
Reference Core Java, Volume I – Fundamentals, Eighth Edition, Chapter 14. Cay S. Horstmann and Gary Cornell. Prentice Hall, 2008
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.