实验十四
1 package 实验十四; 2 3 import java.awt.event.ActionEvent; 4 import java.awt.event.ActionListener; 5 import java.awt.event.KeyEvent; 6 import java.awt.event.KeyListener; 7 import java.util.Timer; 8 import java.util.TimerTask; 9 10 import javax.swing.JButton; 11 import javax.swing.JFrame; 12 import javax.swing.JLabel; 13 import javax.swing.JTextField; 14 15 public class TimeThreadFrame extends JFrame{ 16 /** 17 * 18 */ 19 private static final long serialVersionUID = 1L; 20 // 定义组件 21 private JLabel lblTime; 22 private JTextField txtInput; 23 private JButton btnEnter; 24 // 构造方法 25 public TimeThreadFrame(){ 26 // 设置窗体的相关属性 27 super("TimerThread"); 28 this.setSize(300,200); 29 this.setLayout(null); 30 this.setLocation(100,50); 31 // 创建组件 32 this.lblTime = new JLabel("请输入倒计时时间"); 33 this.lblTime.setBounds(30,20,200,30); 34 this.txtInput = new JTextField(); 35 this.txtInput.setBounds(30,70,100,30); 36 this.btnEnter = new JButton("确定"); 37 this.btnEnter.setBounds(150,70,70,30); 38 // 给JTextField注册监听 39 this.txtInput.addKeyListener(new KeyListener(){ 40 public void keyPressed(KeyEvent ke) {} 41 public void keyReleased(KeyEvent ke) {} 42 public void keyTyped(KeyEvent ke) { 43 //txtInput_KeyTyped(ke); 44 } 45 }); 46 // 给JButton注册监听 47 this.btnEnter.addActionListener(new ActionListener(){ 48 public void actionPerformed(ActionEvent ae){ 49 btnEnter_ActionPerformed(ae); 50 } 51 }); 52 // 将各组件添加到窗体上 53 add(lblTime); 54 add(txtInput); 55 add(btnEnter); 56 // 显示窗体 57 this.setVisible(true); 58 } 59 // 输入时的事件处理,控制用户只能输入数字 60 public void txtInput_KeyTyped(KeyEvent ke){ 61 if(ke.getKeyChar() < '0' || ke.getKeyChar() > '9'){ 62 ke.setKeyChar('\0'); 63 } 64 } 65 // 点击按钮时的事件处理 66 public void btnEnter_ActionPerformed(ActionEvent ae){ 67 // 获得用户输入的倒计时时间 68 String strTime = this.txtInput.getText(); 69 if(strTime.equals("")){ 70 // 检测用户是否输入 71 this.lblTime.setText("您尚未输入,请输入!"); 72 } 73 else{ 74 Integer time = Integer.parseInt(strTime); 75 // 创建线程 76 TimeThread tt = new TimeThread(this.lblTime,time); 77 tt.start(); 78 // 创建Timer 79 Timer timer = new Timer(); 80 timer.schedule(new TimerTask(){ 81 // 启动其他程序 82 public void run() { 83 System.out.print("ok"); 84 } 85 }, time * 1000); 86 } 87 } 88 // 启动窗体 89 public static void main(String[] args){ 90 new TimeThreadFrame(); 91 } 92 } 93 // 时间线程类 94 class TimeThread extends Thread{ 95 private JLabel lblTime; 96 private int time; 97 // 构造方法传入,显示事件的JLabel和倒计时的时间。 98 public TimeThread(JLabel lblTime, int time){ 99 this.lblTime = lblTime; 100 this.time = time; 101 } 102 // run方法 103 public void run(){ 104 while(time > 0){ 105 // 显示所剩时间 106 this.lblTime.setText("所剩时间:" + time+"s"); 107 // 所剩时间减少 108 time--; 109 try { 110 Thread.sleep(1000); 111 }catch (InterruptedException e) { 112 e.printStackTrace(); 113 } 114 } 115 } 116 }
通过本次实验,理解了进程与线程的关系,掌握了创建管理和控制JAVA线程的方法。