Adham Mostafa
Adham Mostafa

Reputation: 33

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

enter image description here

Upvotes: 1

Views: 68

Answers (2)

Suraj Gautam
Suraj Gautam

Reputation: 1590

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.

Upvotes: 2

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4764

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.

Upvotes: 2

Related Questions