import java.util.*;
import java.awt.*;
import java.awt.Point;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
import javax.swing.event.*;
import java.awt.geom.*;
import java.io.*;
public class MyCanvas extends JPanel
{
private Point point; //坐标
private Point point2;
private ArrayList image;
private ArrayList old;
public MyCanvas() {
image = new ArrayList();
old = new ArrayList();
addMouseListener(new MouseHandle());
addMouseMotionListener(new MouseMotionHandle());
}
public void drawImage()
{
Line2D line1 = new Line2D.Double(point.x, point.y, point2.x, point2.y);
image.clear();
image.add(line1);
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.red);
for (int i = 0; i < image.size(); i++) {
Shape s = (Shape)image.get(i);
g2.draw(s);
}
for (int i = 0; i < old.size(); i++) {
Shape s = (Shape)old.get(i);
g2.draw(s);
}
}
private class MouseHandle extends MouseAdapter
{
public void mouseClicked(MouseEvent event){
}
public void mousePressed(MouseEvent event)
{
point = event.getPoint(); //起始坐标
}
public void mouseReleased(MouseEvent event)
{
try
{
old.add(old.size(), image.get(0));
}
catch (IndexOutOfBoundsException e) {}
}
}
private class MouseMotionHandle implements MouseMotionListener
{
public void mouseMoved(MouseEvent event) {}
public void mouseDragged(MouseEvent event)
{
try {
point2 = event.getPoint();
drawImage();
} catch (NullPointerException e) {}
}
}
}
class PaintBoardFrame extends JFrame
{
MyCanvas canvas;
Container container;
public PaintBoardFrame()
{
container = this.getContentPane(); //获得窗口容器
canvas=new MyCanvas();
canvas.setBackground(Color.WHITE);
container.add(canvas);//增加画布
setTitle("简单小画板");//画板的标题
setSize(new Dimension(800, 600));//画板的大小
}
}
class PaintBoard {
public static void main(String[] args) {
// Create application frame.
PaintBoardFrame frame = new PaintBoardFrame();
frame.setVisible(true);
}
}