/** * This is example #4 out of 6, showing a sequence of improvements through * the progression of examples. The six files should be viewed in order. * * This file switches from a 'mouseClicked()' event to a 'mousePressed()' * event, which means that red dots will now be drawn when the mouse * button is pressed DOWN, instead of when the button is released UP. * * This file has its own 'update()' method, which overrides the built-in * (default) method, to call the 'paint()' method. This, along with now * calling the 'repaint()' method (instead of calling 'paint()' directly), * is the best approach, and by having the new 'update()' method contain * only a call to 'paint()', the applet window background is not cleared. * This means that every time the user presses the mouse, the previous red * dots are not erased. * * This example illustrates the appropriate manner in which this program * should be coded, as it is efficient, yet still respectful of other * applets/events/programs running in a multitasking environment. However, * even though one can "sort of" draw by continuously clicking the mouse, * this really is still not yet a drawing program. */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class GraphicsDrawing4 extends Applet { int mouseX = -10; int mouseY = -10; public void init() { setSize(400, 400); setBackground(Color.yellow); addMouseListener(new HandleMouse()); } class HandleMouse extends MouseAdapter { public void mousePressed(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); // Calling the 'repaint' method is the right approach, and // is better than a direct call to 'update' or 'paint' repaint(); } } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { g.setColor(Color.red); g.fillOval(mouseX - 10, mouseY - 10, 20, 20); } }