简体   繁体   English

为什么要打印两次?

[英]Why does this print out twice?

I've noticed that when i use paintComponent in java if I use System.out.println(); 我注意到当我在java中使用paintComponent ,如果我使用System.out.println(); things will print out 2, 3, and sometimes 4 times. 东西会打印出2,3次,有时会打印4次。 I know that when you use extends JPanel it will automatically be called, but why more then once. 我知道当你使用extends JPanel时会自动调用它,但为什么会多一次。

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. System.out.println被调用一次 - 但您的方法可以重复调用。 Everytime paintComponent is called it prints Why? 每次调用paintComponent都会打印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. 这种方法被多次调用,即,对于帧调整大小等,并且反过来使得sysout被执行多次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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