// // FILE: MultiBallWorldFrame.java // AUTHOR: Eugene Wallingford // DATE: 2012/10/11 // COMMENT: a frame with a bunch of moving balls and a button // that causes the balls to move // // MODIFIED: 2012/10/11 -- Eugene Wallingford // CHANGE: changed the button to be a toggle switch that turns // ball movement on and off // import java.awt.Button; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MultiBallWorldFrame extends Frame { private static final int FrameWidth = 600; private static final int FrameHeight = 400; private static final int Iterations = 2000; private Ball[] ball; private int counter; private boolean ballsAreMoving; // new public MultiBallWorldFrame( int numberOfBalls ) { super(); setSize ( FrameWidth, FrameHeight ); setTitle( "Multi Ball World" ); ball = new Ball[numberOfBalls]; for (int i = 0; i < numberOfBalls; i++) { int dx = (int) (20 * Math.random() ); int dy = (int) (10 * Math.random() ); ball[i] = new BoundedBall( 100, 100, 10, dx, dy, this ); } counter = 0; ballsAreMoving = false; // new /* * This is the new code to add our button */ Button move = new Button( "move" ); move.addActionListener( new MoveButtonListener() ); add( "South", move ); } public void paint( Graphics g ) { for (int i = 0; i < ball.length; i++) { ball[i].paint( g ); if ( ballsAreMoving ) // now the program cause balls to move again, ball[i].move(); // but only if the switch is "on" } counter++; if ( counter >= Iterations ) System.exit( 0 ); repaint(); } /* -------------- inner classes -------------- */ private class MoveButtonListener implements ActionListener { public void actionPerformed( ActionEvent e ) { ballsAreMoving = !ballsAreMoving; // new } } }