5

excuse me i search a lot to find how those 3 functions (paint, repaint, paintComponent) interact between them but i have no idea. Can you explain me exactly when they are called ( because sometimes java call it without me asking him) what they do exactly and what is the difference between them. Thank you

mKorbel
  • 109,525
  • 20
  • 134
  • 319
The Answer
  • 279
  • 1
  • 4
  • 11
  • paint is for AWT Components or UI delagate, paintComponent is for Swing JComponent, repaint (programatically) is sheduled refresh JComponent from (Swing) timer or notifier for LayoutManager that revalidate() required repaint (after remove, add, relayout) – mKorbel Jun 01 '13 at 18:05

1 Answers1

7

I am not sure about "paint", but I can explain the relationship between repaint() and paintComponent().

In my limited experience with java, the paintComponent() method is a method in the JPanel class and is a member of "swing".

The paintComponent() method handles all of the "painting". Essentially, it draws whatever you want into the JPanel usings a Graphic object.

repaint() is an inherited instance method for all JPanel objects. Calling [your_JPanel_object].repaint() calls the paintComponent() method.

Every time you wish to change the appearance of your JPanel, you must call repaint().

Certain actions automatically call the repaint() method:

  • Re-sizing your window
  • Minimizing and maximizing your window

to name a few.

IN SHORT paintComponent() is a method defined in JPanel or your own custom class that extends JPanel. repaint() is a method called in another class (such as JFrame) that eventually calls paintComponent().

here is an example:

    public class MyPanel extends JPanel{

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        g.draw([whatever you want]);

        ...
        ...

    }
}
public class MyFrame extends JFrame{

    public MyFrame(){

    MyPanel myPanel = new MyPanel();

    myPanel.repaint();

    }

}
scottysseus
  • 1,922
  • 3
  • 25
  • 50
  • 2
    please be precise: a) _paintComponent() method is a method in the JPanel_ strictly speaking, wrong: it's a method of JComponent, nothing additional done in JPanel b) _adds all of the components (such as JButtons, JTextFields, and other JPanels) into the JPanel usings a Graphic_ wrong: on the contrary, it is explicitly documented to be responsible for painting _itself_ - it has nothing to do with painting its children (which is done in paintChildren) – kleopatra Jul 23 '13 at 06:06
  • Why not call paintComponent() directly, then? – Florian Wicher Mar 26 '22 at 14:59