import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
public class Copy_2_of_PaintLineJFrame extends JFrame {
public class PaintLineCanvas extends Canvas implements MouseListener, MouseMotionListener {
Point start,end,temp;
public PaintLineCanvas() {
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
@Override
public void paint(Graphics g) {
if (start!=null&&temp!=null) {
g.setXORMode(getBackground());
g.setColor(Color.blue);
g.drawLine(start.x, start.y, temp.x, temp.y);
}
if (start!=null&&end!=null) {
g.setColor(Color.blue);
g.drawLine(start.x, start.y, end.x, end.y);
}
}
@Override
public void update(Graphics g) {//如果不写将调用系统的update,那么将用背景色填充canvas,那么前面画的东西就会被自动清除。
paint(g);//响应repaint(),如果不写,也就是说,没有响应方法。
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
start = end = new Point(e.getX(),e.getY());
//repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
temp = end;
end = new Point(e.getX(),e.getY());
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
public Copy_2_of_PaintLineJFrame() {
Dimension dms = getToolkit().getScreenSize();
setBounds(dms.width/4, dms.height/4, dms.width/2, dms.height/2);
getContentPane().add(new PaintLineCanvas());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Copy_2_of_PaintLineJFrame();
}
}