by Dinesh Thakur

The paint () method is called automatically by the environment (usually a web browser) that contains the applet whenever the applet window needs to be redrawn. This happens when the component is first displayed, but it can happen again if the user minimizes the window that displays the component and then restores it or if the user moves another window over it and then move that window out of the way. In addition to these implicit calls to the paint() method by the environment, one can also call the paint () method explicitly whenever the applet window needs to be redrawn, using the repaint () method.

The repaint () method causes the 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. For example: Suppose you want to display the current x and y coordinates of the location where the mouse button is clicked in the applet window. As the applet needs to update information displayed in its window (i.e. redraw the window), each time the mouse is being clicked so this is possible with the use of repaint () method. To sum up, the repaint() method is invoked to refresh the viewing area i.e. you call it when you have new things to display.

import java.awt.*;

import java.applet.Applet;
import java.awt.event.*;
/*<applet code="RepaintJavaExample.class" width="350" height="150"> </applet>*/
public class RepaintJavaExample extends Applet implements MouseListener
{
        private int mouseX, mouseY;
        private boolean mouseclicked = false;
        public void init()
        {
          setBackground(Color.CYAN);
          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 paint( Graphics g )
        {
           String str;
           g.setColor(Color.RED);
           if (mouseclicked)
           {
             str = "X="+ mouseX + "," + "Y="+ mouseY ;
             g.drawString(str,mouseX,mouseY);
             mouseclicked = false;    
           }
        }
}

repaint() in Java Applet Example