//Bouncing.java import java.awt.*; import javax.swing.*; public class Bouncing extends JApplet { int count, size, movesize, naptime; public void init() { String input; input = JOptionPane.showInputDialog( "Enter number of loops" ); count = Integer.parseInt( input ); input = JOptionPane.showInputDialog( "Enter size of circle" ); size = Integer.parseInt( input ); input = JOptionPane.showInputDialog( "Enter distance of move" ); movesize = Integer.parseInt( input ); input = JOptionPane.showInputDialog( "Enter sleep time in ms" ); naptime = Integer.parseInt( input ); } public void paint (Graphics g) { int x=(int)(Math.random()*getWidth()); //random starting int y=(int)(Math.random()*getHeight()); int dir=(int)(Math.random()*4); //random diagonal direction: //0 is NE, 1 is SE, 2 is SW, 3 is NW for (int i=1; i<=count; i++) { g.setColor( Color.WHITE ); g.fillOval(x-size/2,y-size/2,size,size); //erase current circle if (dir == 0) { //moving NE x = x + movesize; y = y - movesize; if (y-size/2 <= 0) //hit top, dir = 1; //change to SE. else if (x+size/2 >= getWidth()) //hit right, dir = 3; //change to NW } else if (dir == 1) { x = x + movesize; y = y + movesize; if (x+size/2 >= getWidth()) dir = 2; else if (y+size/2 >= getHeight()) dir = 0; } else if (dir == 2) { x = x - movesize; y = y + movesize; if (x-size/2 <= 0) dir = 1; else if (y+size/2 >= getHeight()) dir = 3; } else if (dir == 3) { x = x - movesize; y = y - movesize; if (y-size/2 <= 0) dir = 2; else if (x-size/2 <= 0) dir = 0; } g.setColor( Color.RED ); g.fillOval(x-size/2,y-size/2,size,size); try { Thread.sleep(naptime); } catch (InterruptedException e) { } } } }