为什么我的代码执行了两次paintComponent(Graphics page)?
这让我很紧张,这对我来说可能有些愚蠢,但我不明白为什么我的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
.
请也查看这个 SO 问题:paintComponent 正在执行两次
Please see this SO question too: paintComponent is executing twice
相关文章