/** * CircleApplet2.java * Click mouse on applet to show circles * This version shows running the drawing methods in a separate thread. * Interestingly, the inner class which catches the mouse clicked event * implements the interface Runnable. * In contrast with CirclesApplet1a.java which puts the AWT to sleep and * achieves nothing with respect to controlling repaint() requests, this program * puts the programmer defined thread to sleep. This thread runs the loop which * is generating the repaint() calls. While it is sleeping, it cannot invoke repaint(). * This pause gives the AWT thread time to process previous repaint() requests and * execute update() and paint(). * * Sleep times should normally be 10 ms or longer. */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class CirclesApplet2 extends Applet { Canvas canvas; public void init() { setLayout(new GridLayout(1,1)); canvas = new MyCanvas(); add(canvas); } } class MyCanvas extends Canvas { Point currentCenter; Dimension canvasSize; final int RADIUS = 20; public MyCanvas() { setBackground(Color.yellow); currentCenter = new Point(-20,-20); addMouseListener(new HandleMouse()); } class HandleMouse extends MouseAdapter implements Runnable { Thread circleThread = null; public void mousePressed(MouseEvent e) { circleThread = new Thread(this); circleThread.start(); } public void run() { canvasSize = getSize(); // size determined by GridLayout manager and by this applet int x0 = canvasSize.width / 4; int y0 = canvasSize.height / 4; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int x = x0 * (i+1); int y = y0 * (j+1); currentCenter = new Point(x,y); repaint(); try { Thread.sleep(100); } catch (InterruptedException evt) {} } } } } private void drawFillCircle(Graphics g, Color c, Point center, int radius) { g.setColor(c); int leftX = center.x - radius; int leftY = center.y - radius; g.fillOval(leftX, leftY, 2*radius, 2*radius); } public void paint(Graphics g) { drawFillCircle(g, Color.red, currentCenter, RADIUS); } public void update(Graphics g) { paint(g); } }