代码一串&&执行流程
package cn.sisy.awt;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
public class DrawByMouse {
//定义画图区域的大小
private final int width = 500;
private final int height = 500;
//设置起始坐标的位置,这个位置标示鼠标尚未进入myCanvas
private int preX = -1;
private int preY = -1;
//定义一个BufferedImage对象,并获取image对象的Graphics
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
private Frame f = new Frame("手绘测试");
DrawCanvas myCanvas = new DrawCanvas();
//设置画笔默认颜色
private Color foreColor = new Color(255,0,0);
public void init(){
g.fillRect(0, 0, width, height);
myCanvas.setPreferredSize(new Dimension(width,height));
//监听鼠标移动动作
myCanvas.addMouseMotionListener(new MouseMotionAdapter() {
// 实现按下鼠标键并拖动的事件处理器
public void mouseDragged(MouseEvent e){
if(preX>0 && preY>0){
g.setColor(foreColor);
g.drawLine(preX, preY, e.getX(), e.getY());
}
// 将当前鼠标事件点的X、Y座标保存起来
preX = e.getX();
preY = e.getY();
// 重绘drawArea对象
myCanvas.repaint();
}
});
//实现鼠标松开的事件处理器
myCanvas.addMouseListener(new MouseAdapter() {
//实现鼠标松开事件处理
public void mouseReleased(MouseEvent e) {
preX = -1;
preY = -1;
}
});
f.add(myCanvas);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new DrawByMouse().init();
}
class DrawCanvas extends Canvas{
public void paint(Graphics g){
g.drawImage(image,0,0,null);
}
}
}