Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paint, repaint , paintComponent

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

like image 621
The Answer Avatar asked Mar 24 '23 18:03

The Answer


1 Answers

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();

    }

}
like image 166
scottysseus Avatar answered Apr 06 '23 08:04

scottysseus