/* Applet displays a colored dot with randomly selected colors and animates the dot to pop up at random places on the screen in the applet area. */ import java.awt.*; import java.applet.*; import java.lang.Math; public class coloredDot extends Applet implements Runnable { TextField dotSizeField; Thread runner; Button startStop; boolean isRunning = true; // diameter d of dot, which is both its width and height int d = 20; int newSize = -1; // x and y of the dot's position int x = (int)this.size().width/2; int y = (int)this.size().height/2; // array of RGB values of dot's color int[] dot = {0, 0, 0}; public void init() { setBackground(Color.white); this.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 4)); startStop = new Button("Stop"); add(startStop); add (new Label("Size of Dot in Pixels:")); dotSizeField = new TextField(2); add(dotSizeField); } public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void stop() { runner = null; } public void run() { while (isRunning) { try { Thread.sleep(1000); } catch (InterruptedException e) { } repaint(); } } public void paint(Graphics g) { if (isRunning) { g.setColor(Color.white); g.fillRect(0, 0, this.size().width, this.size().height); g.setColor(Color.black); if (this.newSize == -1) { g.drawString("Enter a number", 320, 40); } else { this.d = this.newSize; } g.setColor(new Color(dot[0], dot[1], dot[2])); g.fillOval(x, y, d, d); this.x = (int)(Math.random()*this.size().width); this.y = (int)(Math.random()*this.size().height-24); this.dot[0] = (int)(Math.random()*255); this.dot[1] = (int)(Math.random()*255); this.dot[2] = (int)(Math.random()*255); } // end of if isRunning } public final void update(Graphics g) { paint(g); } public boolean action(Event e, Object arg) { if (e.target instanceof Button) { if (isRunning) { isRunning = false; startStop.setLabel("Start"); stop(); } else { isRunning = true; startStop.setLabel("Stop"); start(); } return true; } if (e.target instanceof TextField) { try { this.newSize = Integer.parseInt(dotSizeField.getText()); } catch (NumberFormatException x) { this.newSize = -1; } return true; } return false; } // end of boolean action } // end of coloredDot