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)?
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
