为什么我的代码执行paintComponent(Graphics page)两次?
这让我很紧张,这对我来说可能是一些愚蠢的事情,但我不明白为什么我的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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它也为我打印了两次。
不过,我认为这不必担心。 Swing 决定何时需要重新绘制。例如,如果您调整窗口大小或最小化/最大化,Swing 将重新绘制。它可能取决于您正在运行的操作系统/硬件。
您编写的代码应该足够健壮,能够处理对
repaint
的多次调用。请参阅这个问题:paintComponent is执行两次
It printed out twice for me too.
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.
You should write your code so that it is robust enough to handle multiple calls to
repaint
.Please see this SO question too: paintComponent is executing twice