我们可以用一个容器把所画图形存储起来,例如数组,队列。
在这里,首先用数组实现画板的重绘。
源代码如下:
import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; public class MyDraw extends JFrame{ int[] array=new int[100]; Graphics g; int x1,y1,x2,y2; int i=0; public static void main(String[] args){ MyDraw draw=new MyDraw(); draw.init(); } public void init(){ this.setTitle("画板重绘的实现"); this.setSize(300, 300); this.setDefaultCloseOperation(3); this.addMouseListener(mls); this.setVisible(true); g=this.getGraphics(); } DrawListener mls=new DrawListener(); public class DrawListener extends MouseAdapter{ public void mousePressed(MouseEvent e){ x1=e.getX(); y1=e.getY(); } public void mouseReleased(MouseEvent e){ x2=e.getX(); y2=e.getY(); i++; array[4*i-4]=x1; array[4*i-3]=y1; array[4*i-2]=x2; array[4*i-1]=y2; g.drawLine(x1, y1, x2, y2); } } public void paint(Graphics g){ //一定要先调用父类的paint 方法,用来绘制窗体。 super.paint(g); System.out.println("paint()"); for(int i=0;i<25;i++){ g.drawLine(array[4*i],array[4*i+1],array[4*i+2],array[4*i+3]); } } }
可是如果用数组,有很大的缺陷,因为数组必须得先定义数组的大小。因此不建议用此方法。