画板的开发_监听_重绘_队列

import java.awt.Graphics;
import java.awt.event.MouseEvent;

public class DrawFrame extends javax.swing.JFrame{
	
	public int x1,y1,x2,y2;
	public int count;
	public Graphics g;
	
	class Shape{
		public int x1,y1,x2,y2;
	}
	
	//调用系统的队列,用以存放图形的坐标
	public java.util.ArrayList<Shape> shapes = new java.util.ArrayList();

	//显示主界面
	public void drawUI(){
		this.setTitle("简易画板");
		this.setBounds(150,25,700,700);
		//窗口大小不可变
		this.setResizable(false);
		
		this.addMouseListener(new java.awt.event.MouseAdapter(){
			public void mouseReleased(MouseEvent e){
				onReleased(e);
			}	
		});
		//关闭窗口时,退出程序
		this.setDefaultCloseOperation(3);
		//窗口可见
		this.setVisible(true);
		//得到画布对象
		g = this.getGraphics();
	}
	
	private void onReleased(MouseEvent e) {
		if(count == 0){
			x1 = e.getX();
			y1 = e.getY();
			count++;
		}else if(count == 1){
			x2 = e.getX();
			y2 = e.getY();
			count--;
			g.drawLine(x1, y1, x2, y2);
			//将坐标存入队列
			Shape shape = new Shape();
			shape.x1 = x1;
			shape.y1 = y1;
			shape.x2 = x2;
			shape.y2 = y2;
			shapes.add(shape);
		}
			
	}
	
	//重绘
	public void paint(Graphics g){
		super.paint(g);
		for(int i=0;i<shapes.size();i++){
			Shape s = shapes.get(i);
			g.drawLine(s.x1, s.y1, s.x2, s.y2);
		}	
	}
	
	//程序入口
	public static void main(String[] args) {
		DrawFrame df = new DrawFrame();
		df.drawUI();
	}
}

 总结:1,须将坐标的数据存放到数组或队列中,不然重绘的时候只会记住最后一直线的坐标。

          2,内部类、匿名类有利于代码的简明。

你可能感兴趣的:(java,swing)