首先,在您的paintComponent
方法中,不要调用
setPreferredSize(new Dimension(500,500));
setVisible(true);
validate();
这将要求重新绘制,导致paintComponent
被召回,你最终会陷入一个令人讨厌的循环,消耗你的 CPU 和(正如你所发现的)你的内存。
如果您可以摆脱它,最好将多边形绘制到缓冲区,然后在paintComponent
. 从长远来看,这将更快......
// Create a field
private BufferedImage buffer;
// Call this when you need to change the polygon some how...
protected void createBuffer() {
// You need to determine the width and height values ;)
buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
int xoffset=5;//Multiply in order to "zoom" the picture
int offset=0;//moves shape to the right
p.addPoint(40*xoffset-offset, 30*xoffset-offset);
p.addPoint(50*xoffset-offset,30*xoffset-offset);
p.addPoint(57*xoffset-offset,37*xoffset-offset);
p.addPoint(57*xoffset-offset,47*xoffset-offset);
p.addPoint(50*xoffset-offset,54*xoffset-offset);
p.addPoint(40*xoffset-offset,54*xoffset-offset);
p.addPoint(33*xoffset-offset,47*xoffset-offset);
p.addPoint(33*xoffset-offset, 37*xoffset-offset);
g.drawPolygon(p);
g.dispose();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (buffer != null) {
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(buffer, translateX, translateY, this);
}
}
更新
所以,无论如何,你正在做的其他有趣的事情是......
- 创建对多边形的静态引用。希望您不打算一次在屏幕上显示更多;)
- 向已经存在的多边形添加新点(每次都
paintComponent
被调用)
- 每次平移多边形
paintComponent
被调用
尝试这样的事情
public class RoundTop extends JPanel {
//Polygons declarations
private Polygon p = new Polygon();
//Translate variables;
private int translateX = 10;
private int translateY = 10;
public RoundTop() {
int xoffset = 5;//Multiply in order to "zoom" the picture
int offset = 0;//moves shape to the right
p.addPoint(40 * xoffset - offset, 30 * xoffset - offset);
p.addPoint(50 * xoffset - offset, 30 * xoffset - offset);
p.addPoint(57 * xoffset - offset, 37 * xoffset - offset);
p.addPoint(57 * xoffset - offset, 47 * xoffset - offset);
p.addPoint(50 * xoffset - offset, 54 * xoffset - offset);
p.addPoint(40 * xoffset - offset, 54 * xoffset - offset);
p.addPoint(33 * xoffset - offset, 47 * xoffset - offset);
p.addPoint(33 * xoffset - offset, 37 * xoffset - offset);
p.translate(translateX, translateY);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawPolygon(p);
g2d.dispose();
}
}