import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class TestMouseLine extends JFrame
{
int x,y;
int endX,endY;
ArrayList list,array;
public TestMouseLine()
{
Container c=getContentPane();
list=new ArrayList();
array=new ArrayList();
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
x=e.getX();
y=e.getY();
}
public void mouseReleased(MouseEvent e)
{
for(int i=0;i<list.size();i++)
array.add(list.get(i));
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
endX = e.getX();
endY = e.getY();
list.clear();
list.add(new MyLine(x,y,endX,endY));
repaint();
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setSize(400,300);
setLocation(400,300);
show();
}
public void paint(Graphics g)
{
super.paint(g);
Iterator it=array.iterator();
while(it.hasNext())
{
MyLine line=(MyLine)it.next();
line.drawMe(g);
}
}
public static void main(String[] args)
{
new TestMouseLine();
}
}
class MyLine
{
private int x,y;
private int endX,endY;
public MyLine(int x,int y,int endX,int endY)
{
this.x = x;
this.y = y;
this.endX = endX;
this.endY = endY;
}
public void drawMe(Graphics g)
{
g.setColor(Color.RED);
g.drawLine(x,y,endX,endY);
}
};
为什么非要画下一条线的时候,才出现上一条线呢?比如:在画第2条线的时候,才出现第一条线...请指教!!!