开发者

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

开发者 https://www.devze.com 2023-02-07 13:23 出处:网络
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\

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()
    {  开发者_StackOverflow社区    
     /*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);

    }



}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消