by Dinesh Thakur

The repaint () method causes then AWT runtime system to execute the update () method of the Component class which clears the window with the background color of the applet and then calls the paint () method. But sometimes erasing the background is undesirable. For example: If user wants to display the x and y coordinates of each location where the mouse is clicked instead of only the currently clicked location then it is not possible using the default version of the update () method. Each time the user clicks in the applets's window, the coordinates of the previously clicked location are erased and only the coordinates of the currently clicked location are displayed. To overcome this problem, it is necessary to override the update () method to invoke paint () directly, thus avoiding the erasure of the component's background.

import java.awt.*;

import java.applet.Applet;
import java.awt.event.*;
/*<applet code="UpdateExample.class" width="350" height="150"> </applet>*/
public class UpdateExample extends Applet implements MouseListener
{
        private int mouseX, mouseY;
        private boolean mouseclicked = false;
        public void init()
        {
          setBackground(Color.black);
          addMouseListener(this);
        }
        public void mouseClicked(MouseEvent e)
        {
          mouseX=e.getX();
          mouseY=e.getY();
          mouseclicked = true;
          repaint();
        }
        public void mouseEntered(MouseEvent e){};
        public void mousePressed(MouseEvent e){};
        public void mouseReleased(MouseEvent e){};
        public void mouseExited(MouseEvent e){};
        public void update(Graphics g)
        {     
          paint(g);
        }
        public void paint( Graphics g)
        {
           String str;
           g.setColor(Color.white);
           if (mouseclicked)
           {
             str = "X="+ mouseX + "," + "Y=" + mouseY;
             g.drawString(str,mouseX,mouseY);
             mouseclicked = false;
           }
        }
}

Update Method in Java Applet Example