简体   繁体   中英

Paint method execute many times

Why this paint function execute many times while I run my code?

I am trying to run this code only one time, but it execute many times, and I don't know why it does that!

public class DrawFrame extends JFrame {

@Override
public void paint(Graphics g) {

    System.out.println("hello Frame");
}
}

public class NJFrame {
public static void main(String[] args) {


    DrawFrame NJFrame = new DrawFrame();
    NJFrame.setSize(1000, 1000);
    NJFrame.setVisible(true);
    NJFrame.setLocation(400, 150);
    NJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

在此处输入图片说明

Well, your code manipulates the JFrame a number of times:

DrawFrame NJFrame = new DrawFrame(); // (1) Create the frame
NJFrame.setSize(1000, 1000);         // (2) Resize the frame
NJFrame.setVisible(true);            // (3) Show the frame
NJFrame.setLocation(400, 150);       // (4) Move the frame

It would seem that each of these operations causes a paint event to be fired, which your paint method handles.

paint method is automatically called whenever it is needed. It's handled by Swing and is invoked when the content pane of your frame needs to be repainted, when the window size is resized, minimized and so on.

For more information, you can explore it.

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