/** * CirclesApplet1a.java * The attempt to control the rapid firing of repaint() requests from a loop * using the standard Thread.sleep() method fails if the loop is running * in the AWT GUI thread which also controls paint(). Since it is asleep it * cannot process the repaint() request anyway. When it awakens it is in * the same situation as before and the repaint() requests still pile up. */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class CirclesApplet1a 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()); } public class HandleMouse extends MouseAdapter { public void mouseClicked(MouseEvent e) { canvasSize = getSize(); // size determined by GridLayout manager and 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); // in this loop, repaint() clogs the AWT thread with // requests to update and paint. Requests are combined // but the result is that parts of the drawing are missing. // The attempt to fix this with Thread.sleep() proves fruitless // because the AWT thread itself is put to sleep so it cannot // process the waiting repaint() request. repaint(); try { Thread.sleep(100); } catch (InterruptedException ex) {} } } } 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); } }