What are the differences between paint() method and repaint() method in Java?


Paint() and Repaint()

  • paint(): This method holds instructions to paint this component. In Java Swing, we can change the paintComponent() method instead of paint() method as paint calls paintBorder(), paintComponent() and paintChildren() methods. We cannot call this method directly instead we can call repaint().
  • repaint(): This method cannot be overridden. It controls the update() -> paint() cycle. We can call this method to get a component to repaint itself. If we have done anything to change the look of the component but not the size then we can call this method.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class PaintRepaintTest extends JPanel implements MouseListener {
   private Vector v;
   public PaintRepaintTest() {
      v = new Vector();
      setBackground(Color.white);
      addMouseListener(this);
   }
   public void paint(Graphics g) { // paint() method
      super.paint(g);
      g.setColor(Color.black);
      Enumeration enumeration = v.elements();
      while(enumeration.hasMoreElements()) {
         Point p = (Point)(enumeration.nextElement());
         g.drawRect(p.x-20, p.y-20, 40, 40);
      }
   }
  public void mousePressed(MouseEvent me) {
      v.add(me.getPoint());
      repaint(); // call repaint() method
   }
   public void mouseClicked(MouseEvent me) {}
   public void mouseEntered(MouseEvent me) {}
   public void mouseExited(MouseEvent me) {}
   public void mouseReleased(MouseEvent me) {}
   public static void main(String args[]) {
      JFrame frame = new JFrame();
      frame.getContentPane().add(new PaintRepaintTest());
      frame.setTitle("PaintRepaint Test");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setSize(375, 250);
      frame.setVisible(true);
   }
}

In the above program, if we click on the screen able to draw squares. In the mousePressed() method, we can call the repaint() method.

Output

Updated on: 10-Feb-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements