This program is set up with two files:
Bouncer is the object to handle the user interface - the buttons. It also starts and stops the thread.
Ball is the thread. It also draws and moves the ball around.
| import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Bouncer extends JPanel implements
ActionListener |
instance variables include buttons to manipulate ball and size of the screen. |
| public Bouncer () { super (new BorderLayout ()); bounce = new Ball (sizex, sizey); //a new selection bounceBall object (other file) setBackground (Color.white); //bounceBall button stuff bounceBall = new JButton ("Start"); bounceBall.setActionCommand ("Start"); bounceBall.addActionListener (this); //reset button stuff //panel & interface stuff |
Set up the screen's buttons. |
| public void actionPerformed (ActionEvent e) { //if bounceBall button is presed if (e.getActionCommand ().equals ("Start")) { //start a new thread and start bouncing the ball Thread bounceBallingThread = new Thread (bounce, "Ballthread"); bounceBallingThread.start (); } else if (e.getActionCommand ().equals ("Stop")) { //stop the thread bounce.stopBall (); } } |
This is where the thread gets started. 'bounce' which is the ball object, gets passed to it. Calling 'start' actually calls the 'run' method in the thread. When the ball is stopped, the 'bounce' object - the ball - is stopped. Not the thread. |
| public static void main (String [] args) { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated (true); //Create and set up the window. //Create and set up the content pane. //Display the window. |
Set up a frame to hold it all. Change the object in the contentPane and the name on the Frame. |
| import java.awt.*; import javax.swing.*; import java.text.*; public class Ball extends JComponent implements Runnable |
Instance Variables for position and direction |
| public Ball (int xx, int yy) { //Pre: xx is how big the screen is in the x direction, yy for the y direction //Post: a new ball is constructed and initialized x = 150; y = 82; dir_x = true; dir_y = true; bound_x = xx; speed = 7; bound_y = (yy); setBackground (Color.white); } |
Constructor; set up the instance variables and set the screen set. |
| public void run () { //run method, starts when "Bounce" button is pressed moveBall (); }
|
Methods that are called from Bouncer. They change the state of the moveBall method - either starting it or stopping it. |
| public void drawBall () { repaint (); }
|
Paints the ball on the screen based on its current location.
|
| public void moveBall () { //calculates the new position of the ball and moves it //repeats until the user clicks the stop button. stopped = false; while (!stopped) drawBall (); //choose new position if (dir_y) //moving up
} |
Redraws the ball. Calculates a new position for the ball. Sleeps for a bit and then repeats! |