在paintComponent()里面加多一个输出语句,可以发现发现protected void
paintComponent(Graphics g)会连续调用两次,想问各位大神什么原理?
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
public class DrawArcs extends JFrame {
public DrawArcs() {
setTitle("DrawArcs");
add(new ArcsPanel());
}
/** Main method */
public static void main(String[] args) {
DrawArcs frame = new DrawArcs();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(250, 300);
}
}
// The class for drawing arcs on a panel
class ArcsPanel extends JPanel {
// Draw four blazes of a fan
int i=0;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println(getWidth()+"+"+getHeight()+"+"+i);
i++;
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);
int x = xCenter - radius;
int y = yCenter - radius;
g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
}
}
paintComponent 方法是由 JPanel 类和其子类重写的,它负责绘制组件的外观。在窗口第一次显示或者窗口大小变化时,系统会自动调用这个方法来绘制组件。
因为在您的程序中第一次调用 paintComponent 时窗口大小是不确定的,所以窗口会把组件绘制两次,第一次绘制的时候窗口的大小是不确定的,所以会先调用一次paintComponent来获取窗口的大小,之后才能正确绘制组件。