- package Package;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import java.util.ArrayList;
- /**
- * @author atlightsgh@gmail.com 2008-11-26
- */
- public class MouseTester {
- public static void main(String[] args) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- new Frame();
- }
- });
- }
- }
- class Frame extends JFrame {
- private final int width = 800;
- private final int height = 600;
- Frame() {
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setTitle("Title");
- this.setSize(width, height);
- this.setVisible(true);
- this.add(new myPanel());
- }
- class myPanel extends JPanel {
- private ArrayList<Line> Lines;
- private Line l;
- myPanel() {
- Lines = new ArrayList<Line>();
- l = new Line();
- setBackground(Color.WHITE);
- MouseListener Listener = new MouseListener();
- addMouseListener(Listener);
- addMouseMotionListener(Listener);
- }
- public void paintComponent(Graphics g) {
- Graphics2D g2 = (Graphics2D) g;
- g2.clearRect(0, 0, width, height);
- for (Line e : Lines) {
- g2.drawLine(e.x1, e.y1, e.x2, e.y2);
- }
- g2.drawLine(l.x1, l.y1, l.x2, l.y2);
- }
- // 鼠标事件响应,同时接受鼠标点击和鼠标移动事件.
- public class MouseListener extends MouseAdapter implements
- MouseMotionListener {
- public void mousePressed(MouseEvent e) {
- l.x1 = e.getX();
- l.y1 = e.getY();
- }
- public void mouseReleased(MouseEvent e) {
- l.x2 = e.getX();
- l.y2 = e.getY();
- try {
- Lines.add(l.clone());
- } catch (CloneNotSupportedException e1) {
- e1.printStackTrace();
- }
- }
- //不断连续画当前鼠标的线
- public void mouseDragged(MouseEvent e) {
- l.x2 = e.getX();
- l.y2 = e.getY();
- myPanel.this.repaint();
- }
- }
- }
- }
- class Line implements Cloneable {
- int x1;
- int y1;
- int x2;
- int y2;
- public Line() {
- x1 = y1 = x2 = y2 = 0;
- }
- public Line clone() throws CloneNotSupportedException {
- return (Line) super.clone();
- }
- private Line(int x1, int y1, int x2, int y2) {
- this.x1 = x1;
- this.y1 = y1;
- this.x2 = x2;
- this.y2 = y2;
- }
- public String toString() {
- return "[x1=" + x1 + ",y1=" + y1 + ",x2=" + x2 + ",y2=" + y2 + "]";
- }
- }