/** * This is example #2 out of 6, showing a sequence of improvements through * the progression of examples. The six files should be viewed in order. * * This file shows a somewhat better approach to handling drawing. The * drawing has been moved from the 'mouseClicked()' event to the 'paint()' * method. However, the 'paint()' method is called directly (a bad policy), * and the background is continuously set to yellow using the graphics * context (by setting a rectangle to be filled with yellow in the 'paint()' * method), which is poor coding, and also unnecessary, since the background * never changes. This is still not a drawing program, since one cannot yet * draw. */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class GraphicsDrawing2 extends Applet { // To avoid a "ghost" red dot when the applet first loads, set the // initial mouse coordinates outside the applet's layout (visible) area private int mouseX = -10; private int mouseY = -10; public void init() { setSize(400, 400); addMouseListener(new HandleMouse()); } class HandleMouse extends MouseAdapter { public void mouseClicked(MouseEvent e) { Graphics g = getGraphics(); mouseX = e.getX(); mouseY = e.getY(); paint(g); // A direct call to 'paint()' is poor program design } } public void paint(Graphics g) { g.setColor(Color.yellow); g.fillRect(0, 0, getSize().width, getSize().height); g.setColor(Color.red); g.fillOval(mouseX - 10, mouseY - 10, 20, 20); } }