Java的Image抽象类与BufferedImage实现类

代码一串&&执行流程

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);
		}
	}	
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值