public class lineDraw extends Applet{
int x1=-1,y1=-1;
boolean flag=true;
int x2,y2;
public void init() {
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
this_mousePressed(e);
}
});
}
void this_mousePressed(MouseEvent e) {
flag=!flag;
if(flag==true) {
x1=e.getX();
y1=e.getY();
}else {
x2=e.getX();
y2=e.getY();
}
if(x1!=-1&&y1!=-1)
repaint();
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawLine(x1, y1, x2, y2);
}
}
运行结果: