简体   繁体   中英

Methods in built-in classes

I am kinda new to java. I was reading java codes to learn more about it, and this had me confused. A method would only be performed if only it is called, right? But how about those methods of built-in classes like paint() , paintComponent() , run() in Runnable class, etc. Are these methods performed without explicitly calling them, once a class that implements these methods is used to instantiate an object? Is that really how it works?

Like for example in this code, method paint() was not really called.

import javax.swing.*;
import java.awt.*;

public class FrameExampleTest{
    public static void main(String args[]){
        FrameExample frame = new FrameExample();
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class FrameExample extends JFrame{
    PanelExample panel;
    public FrameExample(){
        Container c = getContentPane();
        panel = new PanelExample();
        c.add(panel,BorderLayout.CENTER);
    }
}

class PanelExample extends JPanel{
    public PanelExample(){
        setSize(300,200);
    }

    public void paint(Graphics g){
        g.fillArc(20,20,30,30,0,360);
    }
}

You don't call paint or run yourself, but other code in the JVM does call it for you. For instance code inside the Thread class will call your run method. Code inside the event loop will call paint or paintComponent. Over time, you will see that there's nothing magical. Whenever a method is called, some other code calls it.

Yes. The window framework calls paint and paintComponent methods for you. It figures out when the paint/repaint is required (eg when window is moved, opened, re-opened, resized, etc). Javadoc to these methods sometimes mentions it isn't advised/not required to call them directly, but is required to implement them to do such and such things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM