最近做模拟Buffon投针,要在一个panel上模拟多次投针的动作,调用paint绘制“针”时,总是会把上次绘制的擦除掉...注释掉super.paint虽然可以防止擦除,但是整个panel的布局都会毁掉。
解决方法,使用bufferImage,每一次投针动作,都把针画到bufferImage对象中,paint bufferImage对象。
package buffonneedle;
import java.awt.Color;
public class BuffonPanel extends JPanel{
private static final long serialVersionUID = -4803828492748385106L;
BuffonSimulate bs = new BuffonSimulate();
int x1=0,y1=0,x2=0,y2=0;
private Image pic = createImage(1000, 500, true);
private Graphics graphics = pic.getGraphics();
final static public BufferedImage createImage(int width, int height,boolean flag){
if (flag) {
return new BufferedImage(width, height, 2);
} else {
return new BufferedImage(width, height, 1);
}
}
@Override
public void update(Graphics g) {
graphics.setColor(Color.black);
int loop = BuffonSimulate.ScreenHeight/BuffonSimulate.RowHeight;
for(int i=0;i<=loop;i++){
graphics.drawLine(0, i*BuffonSimulate.RowHeight, BuffonSimulate.ScreenWidth, i*BuffonSimulate.RowHeight);
}
graphics.drawLine(x1, y1, x2, y2);
g.drawImage(pic, 0, 0, null);
g.dispose();
}
@Override
public void paint(Graphics g) {
super.paint(g);
update(g);
}
public boolean startSimulate(){
Point[] p = bs.Simulate();
boolean isCross = bs.isIntersection(p);
x1 = p[0].x;
y1 = p[0].y;
x2 = p[1].x;
y2 = p[1].y;
repaint();
return isCross;
}
}