简体   繁体   中英

Why does this print out twice?

I've noticed that when i use paintComponent in java if I use System.out.println(); things will print out 2, 3, and sometimes 4 times. I know that when you use extends JPanel it will automatically be called, but why more then once.

Here is some code to try yourself.

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

public class stack extends JPanel{
public stack(){
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.add(this);
    frame.setLocationRelativeTo(null);
    frame.setSize(200, 200);
    }
public static void main(String args[]){
    stack s = new stack();
    }
public void paintComponent(Graphics g){
    super.paintComponents(g);
    g.drawString("Thank You!", 100, 100);
    System.out.println("Why?");
}
}

System.out.println gets called once - but your method could be called repeatedly. Everytime paintComponent is called it prints Why? .

This method is being called multiple times, ie, for frame resizes or such and in turn makes it appear that sysout is being executed more than once.

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