我们学习了自定义队列,那么下面我们就可以来实现我们画板的重绘了!
下面分析一下重绘的过程,每次画上去以后,我们就要记录这次画的是什么形状,起始坐标和中止坐标。
然后把坐标和形状放入自定义类存入队列中,然后在面板的重绘过程中遍历队列重新画出来,画板的重绘就实现啦~~
首先我们新建一个Shape类:
public class Shape {
private String shape;
private int x1, y1, x2, y2;
/**
* 构造方法
* @param x1
* @param y1
* @param x2
* @param y2
* @param shape
*/
public Shape(int x1, int y1, int x2, int y2, String shape) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.shape = shape;
}
/**
* 画图形的方法
* @param g
*/
public void draw(Graphics g) {
//如果是直线就画线
if (shape.equals("Line")) {
g.drawLine(x1, y1, x2, y2);
}else{
//判断使x1和y1最小
if (x1 > x2) {
int t = x1;
x1 = x2;
x2 = t;
}
if (y1 > y2) {
int t = y1;
y1 = y2;
y2 = t;
}
//如果图形是三角形
if (shape.equals("Rectangle")) {
g.drawRect(x1, y1, x2 - x1, y2 - y1);
}
//如果图形是圆角矩形
if (shape.equals("RoundRect")) {
g.drawRoundRect(x1, y1, x2 - x1, y2 - y1, 20, 20);
}
//如果矩形是圆
if (shape.equals("Round")) {
//计算半径
int r = Math.min(x2 - x1, y2 - y1);
g.drawOval(x1, y1, r, r);
}
}
}
}
然后在监听器的鼠标按键那设置一下:
/**
* 鼠标按下,获取坐标x1,y1
*/
public void mousePressed(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();
}
/**
* 鼠标释放,获取坐标x2,y2
*/
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
// 如果点的是三角形
if (dt.getshape().equals("Triangle")) {
if (bol) {
//创建图形对象
shape = new Shape(x1, y1, x2, y2, "Line");
//画图形
shape.draw(dt.getGraphics());
//将图形添加到队列
list.add(shape);
//添加坐标
tx1 = x1;
ty1 = y1;
tx2 = x2;
ty2 = y2;
bol = false;
} else {
//创建图形对象
shape = new Shape(tx1, ty1, x2, y2, "Line");
//将图形添加到队列
list.add(shape);
//画图形
shape.draw(dt.getGraphics());
//创建图形对象
shape = new Shape(tx2, ty2, x2, y2, "Line");
//将图形添加到队列
shape.draw(dt.getGraphics());
//画图形
list.add(shape);
bol = true;
}
} else {
//如果不是三角形,新建画图对象,输入坐标和形状
shape = new Shape(x1, y1, x2, y2, dt.getshape());
//将图形添加至队列
list.add(shape);
//画出图形
shape.draw(dt.getGraphics());
}
}
最后在面板上进行重绘就完成了!
public void paint(Graphics g) {
super.paint(g);
for (int i = 0; i < dl.getList().size(); i++) {
// 将队列中的图形画出来
((Shape) dl.getList().get(i)).draw(g);
}
}
如果我们想添加一个按钮清除屏幕上的痕迹,就可以:
JButton Clear = new JButton("Clear");
Clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//清除队列
dl.getList().clear();
//重绘窗体
jf.repaint();
}
});