正文

书上的线程GUI2006-04-05 00:25:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/sword2008/11953.html

分享到:

import java.awt.*;import java.awt.event.*;public class Welcome extends WindowAdapter implements ActionListener{ Frame f; static Welcome.Thread3 wt1,wt2; public static void main(String args[]){  Welcome w=new Welcome();  w.display();  wt1=w.new Thread3("welcome!");  wt2=w.new Thread3("how are you?");  wt2.start();  wt2.setButton(); } public void display(){  f=new Frame("welcome");  f.setSize(400,240);  f.setLocation(200,140);  f.setBackground(Color.lightGray);  f.setLayout(new GridLayout(4,1));  f.addWindowListener(this);  f.setVisible(true); } public class Thread3 extends Thread{  Panel p1;  Label lb1;  TextField tf1,tf2;  Button b1,b2;  int sleeptime=(int)(Math.random()*100);  public Thread3(String str){   super(str);   for(int i=0;i<100;i++)   str=str+"";   tf1=new TextField(str);   f.add(tf1);   p1=new Panel();   p1.setLayout(new FlowLayout(FlowLayout.LEFT));   lb1=new Label("sleep");   tf2=new TextField(""+sleeptime);   p1.add(lb1);   p1.add(tf2);   b1=new Button("启动");   b2=new Button("中断");   p1.add(b1);   p1.add(b2);   b1.addActionListener(new Welcome());   b2.addActionListener(new Welcome());   f.add(p1);   f.setVisible(true);     }  public void run(){   String str;   while(this.isAlive()&&!this.isInterrupted()){    try{     str=tf1.getText();     str=str.substring(1)+str.substring(0,1);     tf1.setText(str);     this.sleep(sleeptime);    }    catch(InterruptedException e){     System.out.println(e);     break;    }   }  }  public void setButton(){   if(this.isAlive()) b1.setEnabled(false);   if(this.isInterrupted()) b2.setEnabled(false);   } } public void windowClosing(WindowEvent e){  System.exit(0); } public void actionPerformed(ActionEvent e){  if((e.getSource()==wt1.b1)||(e.getSource()==wt1.b2))  actionPerformed(e,wt1);  if((e.getSource()==wt2.b1)||(e.getSource()==wt2.b2))  actionPerformed(e,wt2); } public void actionPerformed(ActionEvent e,Thread3 wt1) {if(e.getSource()==wt1.b1){  wt1.sleeptime=Integer.parseInt(wt1.tf2.getText());  wt1.start(); } if(e.getSource()==wt1.b2) wt1.interrupt(); wt1.setButton(); } }

阅读(14412) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册