/** * This is example #3 out of 6, showing a sequence of improvements through * the progression of examples. The six files should be viewed in order. * * This file shows an even better approach to handling drawing. The * background color (yellow) is now set in the 'init()' method, and it is * done properly (using the 'setBackground()' method). After that, the * built-in (default) 'update()' method is being used to automatically handle * the background, while 'paint()' just updates the red dot. The 'update()' * method first refreshes (clears) the applet window background, and then * calls 'paint()'. The 'update()' method is called directly, which is not * the best programming practice. Once again, this is still not a drawing * program. */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class GraphicsDrawing3 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 mouseClicked(MouseEvent e) { Graphics g = getGraphics(); mouseX = e.getX(); mouseY = e.getY(); update(g); // A direct call to 'update()' is not a good idea } } public void paint(Graphics g) { g.setColor(Color.red); g.fillOval(mouseX - 10, mouseY - 10, 20, 20); } }