涂鸦是一个在网络聊天中经常会用到的工具,由于笔者水平有限,只能说下一个简单的涂鸦,就是在面板中可以用画笔自己花一些东西。我使用的是画实心矩形(或者圆形)来达到目的,通过监听鼠标事件来获得鼠标点击的坐标,即使用 e.getX( ), e.getY( ) 来获得鼠标点击出的坐标,然后将这个坐标存到容器中,以便在 重写 paint()方法是使用,来达到画出痕迹的效果。 Point 类是做前面的程序时候留下的,我顺便用了下。Point类写的就是一个 点 的类。
package com.lovo;
/**
* 本程序是写的是一个 “点” 的类
* @author 杜海
*
*/
public class Point {
private int x,y;
/**
* 定义了一个空构造器
*/
public Point() {
}
/**
* 定义了一个含有参数x,y的构造器
* @param x
* @param y
*/
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
/**
* 计算两点之间的距离
* @param p1
* @return
*/
public double distance(Point p1){
return Math.sqrt((x-p1.x)*(x-p1.getX())+(y-p1.getY())*(y-p1.getY()));
}
/**
* @return the x 得到x
*/
public int getX() {
return x;
}
/**
* @return the y 得到y
*/
public int getY() {
return y;
}
/**
* @param x the x to set
*/
public void setX(int x) {
this.x = x;
}
/**
* @param y the y to set
*/
public void setY(int y) {
this.y = y;
}
}
package com.lovo;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* 本程序是写的一个简单的涂鸦程序,通过鼠标监听来获得相应屏幕的坐标
* @author Administrator
*
*/
@SuppressWarnings("serial")
public class Painting extends JFrame {
private Image offimage=new BufferedImage(500,400,1); //使用双缓冲来解决屏幕闪动
private Point p1 = new Point(), p2 = new Point();
private List<Point> list = new ArrayList<Point>();
public Painting() {
this.setTitle("画图");
this.setSize(500, 400);
this.setResizable(false);
this.setLayout(null);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.addMouseListener(new MouseAdapter() { //鼠标监听 获得屏幕坐标
@Override
public void mouseReleased(MouseEvent e) {
p1.setX(e.getX());
p1.setY(e.getY());
p2 = new Point(p1.getX(), p1.getY());
list.add(p2);
repaint();
}
});
}
/**
* 重写paint 方法
*/
@Override
public void paint(Graphics g) {
Graphics offG=offimage.getGraphics();
super.paint(offG);
offG.setColor(Color.BLUE);
Graphics2D g2d=(Graphics2D) offG;
g2d.setStroke(new BasicStroke(5));
System.out.println(list.size());
for (int i = 0; i < list.size() ; i++) {
int x1 = list.get(i).getX();
int y1 = list.get(i).getY();
offG.fillRect(x1-5, y1-5, 10, 10);
}
g.drawImage(offimage, 0, 0, null);
}
/**
*main 函数的入口
* @param args
*/
public static void main(String[] args) {
new Painting().setVisible(true);
}
}