画板重绘的实现

画板重绘的实现

在完成之前的功能之后,我们发现当改变窗体大小之后,之前我们在窗体上绘制的图形会消失

这是因为承载我们图形的窗体也是画出来的,在改变大小之后是对窗体和组件进行了重绘

但是不会对我们之前画的图形进行重绘

所以我们需要对我们之前画的图形进行存储,然后在对窗体重绘之后进行重新绘制

首先我们定义一个容器数组(Shape)类用来存储我们所画图形的数据

public class Shape {
	private int x1,x2,x3,y1,y2,y3,x,y;
	private ImageIcon img;
	private Color color=Color.black;
	private String type="直线";
	private Stroke stroke;
	private Graphics g;
	
	public void setG(Graphics gr){
		g=(Graphics2D)gr;
	}
	public Shape(int x,int y,int x1,int x2,int x3,int y1,int y2,int y3,Color color,String type,Stroke sroke){
		this.x1=x1;
		this.x=x;
		this.y=y;
		this.x2=x2;
		this.x3=x3;
		this.y1=y1;
		this.y2=y2;
		this.y3=y3;
		this.color=color;
		this.type=type;
		this.stroke=stroke;
		
		
		
		
	}

然后重写写重绘的方法(我们这里以直线举例)

public void draw(Graphics g){
		g.setColor(color);
		if(type.equals("直线")){
			g.setColor(color);
    		g.drawLine(x1, y1, x2, y2);//画直线
		}
}

然后在DrawListener里画完直线之后进行存储

Shape[] shapes=new Shape[1000000];
	private int i;

 public void mouseReleased(MouseEvent e){
    	System.out.println("鼠标释放了!");
    	x2=e.getX();
    	y2=e.getY();
    	
    	
    	//调用画图的方法
    	if(command.equals("直线")){
    		g.setColor(co);
    		g.drawLine(x1, y1, x2, y2);//画直线
    		
	 }

Shape s=new Shape(x,y,x1, x2, x3, y1, y2, y3, co, command, stroke);
	shapes[i++]=s;
	Draw dr=new Draw();
	dr.setshape(shapes);

将DrawListener里存储的数组传递过来之后,Draw主函数里在在重绘窗体之后调用数组里存储的数据并重新绘制图案

shapes=dl.shapes;
public void paint(Graphics g){
		//调用父类的方法重绘组件
		super.paint(g);
		
		for(int i=0;i<shapes.length;i++){
			Shape s=shapes[i];
			//如果s为空则不执行
			if(s!=null){
			s.draw(g);
			}
		}
	}

这是再当我们改变窗体大小之后,原来的图形不会消失,也会被重新绘制。

到这里我们的画图板就完成了。

猜你喜欢

转载自blog.csdn.net/qq_41819698/article/details/81984579