【问题标题】:why is my code executing paintComponent(Graphics page) twice?为什么我的代码执行了两次paintComponent(Graphics page)?
【发布时间】:2011-06-16 09:41:22
【问题描述】:

这让我很紧张,这对我来说可能有些愚蠢,但我不明白为什么我的 paintComponent 被调用了两次,如果你运行我的代码,它会输出 REPEAT?重复?两次,我不希望它这样做.. 那么它为什么会这样做,我该如何解决呢?

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

    }



}

【问题讨论】:

  • 我运行你的代码,而paintComponent 只运行一次。它打印重复?只有一次。
  • 真的吗?我的java安装有什么问题吗? eclipse和netbeans中的JavaSE-1.6.0_22,它导致REpEAT?两次
  • @novar:是的。我也在使用 JRE6 和 eclipse。它在我的机器上运行良好。
  • 嗯,知道为什么机器会运行两次吗?
  • 注释掉的代码有多复杂?问题的根源可能在于该代码。

标签: java swing components drawing paint


【解决方案1】:

我也打印了两次。

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

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

请也查看这个 SO 问题:paintComponent is executing twice

【讨论】:

  • 是的 ^ 那是我之前的问题,嗯。好的,谢谢,我只是想知道为什么 Swing 决定重新粉刷..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多