why is my code executing paintComponent(Graphics page) twice?(为什么我的代码执行了两次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
这篇关于为什么我的代码执行了两次paintComponent(Graphics page)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我的代码执行了两次paintComponent(Graphics page)?
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01