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


- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01