Paint, repaint , paintComponent

后端 未结 1 345
谎友^
谎友^ 2021-01-06 04:18

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 ca

相关标签:
1条回答
  • 2021-01-06 05:04

    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();
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题