/** * CirclesApplet.java * Click on the applet to draw the circles. * This version just uses the system provided AWT GUI thread. * The simplest way to make monothreaded graphics programs work is to * avoid repaint() and, instead, get a graphics context with getGraphics() * and call update() directly as shown here. * Calling update() or paint() directly is not really good policy because * other applets on the web page also depend on the AWT thread. Your applet may * become rude to these others by hogging this important thread. * See CircleApplet2.java for example using its own thread. * See CircleApplet1a.java for (failed) attempts ot use * the more cooperative repaint() in a monothreaded applet. */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class CirclesApplet extends Applet { Canvas canvas = new MyCanvas(); public void init() { setLayout(new GridLayout(1,1)); 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) { Graphics g = getGraphics(); 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); update(g); } } } 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); } }