why is my code executing paintComponent(Graphics page) twice?

五迷三道 提交于 2019-12-29 01:58:06

问题


This is getting on my nerves and it probably something silly on my part but I can't figure out why my paintComponent is being called twice, if you run my code it outputs REPEAT? REPEAT? twice, I don't want it to do that.. So why does it do it and how can I fix it?

import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;

public class Main extends JPanel {


    public Main()
    {      
     /*code here*/
    }

    public void paintComponent(Graphics page)
    {
     clear(page);

        /*code here*/

        System.out.println("REpEAT?"); 

    }

    protected void clear(Graphics page) {
        super.paintComponent(page);
      }

    public static void main (String[] args)
    {
        JFrame frame = new JFrame ("Circles");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.getContentPane().add(new Main());
        frame.setVisible(true);

    }



}

回答1:


It printed out twice for me too.

However, I don't think it is cause for concern. Swing decides when things need to be repainted. For example, if you resize a window or minimise/maximise, Swing will repaint. It might be dependent on the OS/hardware you are running on.

You should write your code so that it is robust enough to handle multiple calls to repaint.

Please see this SO question too: paintComponent is executing twice



来源:https://stackoverflow.com/questions/4814289/why-is-my-code-executing-paintcomponentgraphics-page-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!