import javax.swing.JFrame;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.Color;
public class Line extends JFrame {
private int startx,starty,endx,endy;
private Canvas can;/画布
public Line(){
super("line");
this.setSize(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
can=new Canvas();
getContentPane().add(can);
can.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
startx=e.getX();
starty=e.getY();
}
public void mouseReleased(MouseEvent e){
can.getGraphics().setColor(Color.green);
can.getGraphics().drawLine(startx,starty,endx,endy);
}
});
can.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){//点下左键 拖动松开可出现直线
endx=e.getX();
endy=e.getY();
}
});
}
public static void main(String args[]){
new Line().setVisible(true);
}
}
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.Color;
public class Line extends JFrame {
private int startx,starty,endx,endy;
private Canvas can;/画布
public Line(){
super("line");
this.setSize(300,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
can=new Canvas();
getContentPane().add(can);
can.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
startx=e.getX();
starty=e.getY();
}
public void mouseReleased(MouseEvent e){
can.getGraphics().setColor(Color.green);
can.getGraphics().drawLine(startx,starty,endx,endy);
}
});
can.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){//点下左键 拖动松开可出现直线
endx=e.getX();
endy=e.getY();
}
});
}
public static void main(String args[]){
new Line().setVisible(true);
}
}