为什么我的代码两次执行paintComponent(“图形"页面)? [英] why is my code executing paintComponent(Graphics page) twice?

查看:132
本文介绍了为什么我的代码两次执行paintComponent(“图形"页面)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我感到不安,这可能对我来说很愚蠢,但我不知道为什么两次调用我的paintComponent,如果运行我的代码,它会输出REPEAT?重复?两次,我不希望它那样做..那么为什么要这样做,以及如何解决呢?

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

    }



}

推荐答案

它也为我打印了两次.

但是,我不认为这值得关注. Swing决定何时需要重新粉刷东西.例如,如果您调整窗口大小或最小化/最大化,Swing将重新绘制.它可能取决于您所运行的操作系统/硬件.

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.

您应该编写代码,使其足够健壮,以处理对repaint的多次调用.

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

也请参见此问题: paintComponent执行两次

这篇关于为什么我的代码两次执行paintComponent(“图形"页面)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆