//Ball3 //illustrates object oriented thinking // The ball with the option to change colors // ...and the bounce method import java.awt.*; import java.applet.*; public class Ball3 extends Applet implements Runnable{ int size; Color color; int xVal = 10; //X value of ball int yVal = 10; //Y value of ball boolean bounceIt = false; //says whether ball is bouncing boolean goingUp = false; //says whether ball is going up or down Button cmdRed = new Button("Red"); Button cmdBlue = new Button("Blue"); Button cmdBounce = new Button("Bounce: Off"); Thread runner; public void start(){ if (runner == null){ runner = new Thread(this); runner.start(); } // end if } // end start; public void stop(){ if (runner != null){ runner.stop(); runner = null; } // end if } // end stop public void run(){ while(true){ //that wacky endless loop! if (bounceIt == true){ //set new y value if (goingUp){ //going up yVal -= 10; //check for minimum size if (yVal < 0){ goingUp = false; } // end if }else{ //going down yVal += 10; //check for maximum size if (yVal > this.size().height-20){ goingUp = true; } // end yVal if } // end goingUp if //change X value of ball xVal += 10; //check for maximum size if(xVal > this.size().width -20){ xVal = 10; } // end xval if //pause with exception handling try { Thread.sleep(250); } catch (Exception e){ showStatus(e.toString()); } // end exception handle //draw the ball in its new position repaint(); } // end bounceIt if } // end while } // end run public void init(){ add(cmdRed); add(cmdBlue); add(cmdBounce); } // end init public void paint(Graphics g){ g.setColor(color); g.fillOval(xVal,yVal,20,20); } public boolean action(Event e, Object o){ if (e.target == cmdRed){ this.color = Color.red; repaint(); return true; }else if(e.target == cmdBlue){ this.color = Color.blue; repaint(); return true; }else if(e.target == cmdBounce){ bounceIt = !bounceIt; if (bounceIt == true){ cmdBounce.setLabel("Bounce: On"); }else{ cmdBounce.setLabel("Bounce: Off"); } // end bounceIt if return true; }else{ return false; } // end if } // end action }// end class definition