//DrawLine.java package myprojects.drawline; public class DrawLine { public static void main(String[] args) { // TODO: Add your code here MyFrame f=new MyFrame(); f.setSize(500,500); f.setTitle("MyFrame"); f.setVisible(true); System.out.println("start!"); } }
//MyFrame.java package myprojects.drawline; import java.util.*; import java.awt.Frame; import java.awt.*; import java.awt.event.*; public class MyFrame extends Frame { int x1,x2,y1,y2; Vector v=new Vector(); public MyFrame(){ enableEvents(AWTEvent.MOUSE_EVENT_MASK); enableEvents(AWTEvent.WINDOW_EVENT_MASK); } protected void processMouseEvent(MouseEvent e){ if(e.getID()==MouseEvent.MOUSE_PRESSED){ x1=e.getX(); y1=e.getY(); } if(e.getID()==MouseEvent.MOUSE_RELEASED){ x2=e.getX(); y2=e.getY(); Graphics g=getGraphics(); g.setColor(Color.red); g.setFont(new Font("隶书",Font.ITALIC,30));//设置文本字体 g.drawString(new String(x1+","+y1),x1,y1);//坐标文本和按下鼠标时的坐标 g.drawLine(x1,y1,x2,y2); g.drawString(new String(x2+","+y2),x2,y2); v.addElement(new MyLine(x1,y1,x2,y2)); } } protected void processWindowEvent(WindowEvent e){ if(e.getID()==WindowEvent.WINDOW_CLOSING){ dispose(); } } public void paint(Graphics g){ /* g.setColor(Color.red); g.setFont(new Font("隶书",Font.ITALIC,30));//设置文本字体 g.drawString(new String(x1+","+y1),x1,y1);//坐标文本和按下鼠标时的坐标 g.drawLine(x1,y1,x2,y2); g.drawString(new String(x2+","+y2),x2,y2); */ Enumeration e=v.elements(); while(e.hasMoreElements()){ MyLine ln=(MyLine)e.nextElement(); Thread.sleep(5000); ln.drawLine(g); } } }
//MyLine.java package myprojects.drawline; import java.awt.*; public class MyLine { int x1,x2,y1,y2; public MyLine(int x1,int y1,int x2,int y2){ this.x1=x1; this.y1=y1; this.x2=x2; this.y2=y2; } public void drawLine(Graphics g){ g.setColor(Color.red); g.setFont(new Font("隶书",Font.ITALIC,30));//设置文本字体 g.drawString(new String(x1+","+y1),x1,y1);//坐标文本和按下鼠标时的坐标 g.drawLine(x1,y1,x2,y2); g.drawString(new String(x2+","+y2),x2,y2); } }