问题
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);
}
}
回答1:
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
来源:https://stackoverflow.com/questions/4814289/why-is-my-code-executing-paintcomponentgraphics-page-twice