正在加载图片...
public static void main(String]args) new Test4(); import iava awt * import java.awt.event.*; import javax age bufferedimage:∥程序中用到缓冲区画图 import java.util.ArrayList:使用ArrayList保存鼠标拖动路径上的所有点 public class DrawPanel extends JPane implements MouseMotionListener int width=400,height=400 DRAW-1.CLEAR-2. ArrayList array=new ArrayList(:)/∥保存鼠标移动路径上的点坐标 Bufferedl nage bufflmage,∥图像线 中区 Graphics2Dgg∥图像缓冲区画笔 public DrawPanel(构造方法 Color..white)/设置面板背景色为白色 ∥创建图像缓冲区,大小为480、400 bufflmage new BufferedImage(width,height e.I gg fillRect(O,0,widh,height,)/画缓冲区的白色背景 (his,∥对面板增加鼠标监听 /把鼠标拖动路径上的点先画在缓冲区中,再把缓冲区画在在面板中 Graphics g) Graphics.2Dg2d-(Graphics2D)g,/把父类对象强制转化为子类对象 if(state-=DRAW){/state值为I,表示画图 个0缓区百笔的宽度 for(inti0 iarray..sizc0-l:i)循环ary的所有点 下一个占 邻两占间的 CLEAR){/sae值为2 除面截 上的国 ound()) 背景颜色whit 把缓冲区中的画图显示在面板上 g2d.drawlmage(bufflmage.0.0.width.height.,this). 55 public static void main(String[] args){ new Test4(); } } ////////////////////////////////////////////// DrawPanel.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.image.BufferedImage; //程序中用到缓冲区画图 import java.util.ArrayList; //使用 ArrayList 保存鼠标拖动路径上的所有点 public class DrawPanel extends JPanel implements MouseMotionListener { int width=400,height=400; static final int DRAW=1,CLEAR=2; int state=0; ArrayList array=new ArrayList();//保存鼠标移动路径上的点坐标 BufferedImage buffImage;//图像缓冲区 Graphics2D gg;//图像缓冲区画笔 public DrawPanel() {//构造方法 setBackground(Color.white);//设置面板背景色为白色 //创建图像缓冲区,大小为 480、400 buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB ); gg = buffImage.createGraphics();//创建缓冲区画笔 gg.setColor(Color.white); //设置缓冲区画笔颜色 gg.fillRect(0,0,width,height); //画缓冲区的白色背景 addMouseMotionListener(this); //对面板增加鼠标监听 } //把鼠标拖动路径上的点先画在缓冲区中,再把缓冲区画在在面板中 public void paint( Graphics g ) { super.paint(g); gg.setColor(Color.red); Graphics2D g2d=(Graphics2D)g;//把父类对象强制转化为子类对象 if(state==DRAW){//state 值为 1,表示画图 gg.setStroke(new BasicStroke(3.0f));//设置缓冲区画笔的宽度 Point p1,p2;//声明两个点类对象 for(int i=0;i<array.size()-1;i++) {//循环 array 的所有点 p1=(Point)array.get(i); //得到第 1 个点 p2=(Point)array.get(i+1); //得到相邻的下一个点 gg.drawLine(p1.x,p1.y,p2.x,p2.y);//画相邻两点间的线 } } else if(state==CLEAR){//state 值为 2,表示清除面板上的画图 gg.setColor(getBackground()); //设置缓冲区画笔为当前背景颜色 white gg.fillRect(0,0,width,height); //画缓冲区为背景颜色---清除画图 } //把缓冲区中的画图显示在面板上 g2d.drawImage(buffImage,0,0,width,height,this); }
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有