方法一:
1 package C5; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 6 import javax.swing.JFrame; 7 import javax.swing.JLabel; 8 import javax.swing.JOptionPane; 9 import javax.swing.JPanel; 10 import javax.swing.JTextField; 11 12 public class CountdownTimer extends Thread { 13 JTextField tf; 14 JLabel l; 15 JFrame fr; 16 17 public void run() { 18 buildGUI(); 19 } 20 21 void display() { 22 for (int i = 60; i >= 0; i--) { 23 try { 24 Thread.sleep(1000); 25 String s = Integer.toString(i); 26 27 tf.setText(" " + s + "second to go.."); 28 29 } catch (Exception e) { 30 System.out.println(e); 31 } 32 } 33 JOptionPane.showMessageDialog(fr, "Time up !!!!!!!!"); 34 tf.setText(""); 35 tf.setEditable(false); 36 } 37 38 public void buildGUI() { 39 fr = new JFrame("Countown Timer"); 40 JPanel p = new JPanel(); 41 l = new JLabel(""); 42 tf = new JTextField(15); 43 44 tf.setEnabled(false); 45 Font f = new Font("Verdana", 0, 18); 46 tf.setFont(f); 47 tf.setBackground(Color.black); 48 p.setBackground(Color.blue); 49 fr.add(p); 50 p.add(tf); 51 p.add(l); 52 fr.setVisible(true); 53 fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 54 fr.setSize(300, 100); 55 fr.setResizable(false); 56 display(); 57 58 } 59 60 public static void main(String args[]) { 61 CountdownTimer obj = new CountdownTimer(); 62 // Thread countthread =new Thread(); 63 obj.start(); 64 } 65 66 }
方法二:
1 package C5; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 6 import javax.swing.JFrame; 7 import javax.swing.JLabel; 8 import javax.swing.JOptionPane; 9 import javax.swing.JPanel; 10 import javax.swing.JTextField; 11 12 public class CountdownTimer implements Runnable { 13 JTextField tf; 14 JLabel l; 15 JFrame fr; 16 17 public void run() { 18 buildGUI(); 19 } 20 21 void display() { 22 for (int i = 60; i >= 0; i--) { 23 try { 24 Thread.sleep(1000); 25 String s = Integer.toString(i); 26 27 tf.setText(" " + s + "second to go.."); 28 29 } catch (Exception e) { 30 System.out.println(e); 31 } 32 } 33 JOptionPane.showMessageDialog(fr, "Time up !!!!!!!!"); 34 tf.setText(""); 35 tf.setEditable(false); 36 } 37 38 public void buildGUI() { 39 fr = new JFrame("Countown Timer"); 40 JPanel p = new JPanel(); 41 l = new JLabel(""); 42 tf = new JTextField(15); 43 44 tf.setEnabled(false); 45 Font f = new Font("Verdana", 0, 18); 46 tf.setFont(f); 47 tf.setBackground(Color.black); 48 p.setBackground(Color.blue); 49 fr.add(p); 50 p.add(tf); 51 p.add(l); 52 fr.setVisible(true); 53 fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 54 fr.setSize(300, 100); 55 fr.setResizable(false); 56 display(); 57 58 } 59 60 public static void main(String args[]) { 61 CountdownTimer obj = new CountdownTimer(); 62 Thread countthread =new Thread(obj); 63 countthread.start(); 64 } 65 66 }
注:两个方法比较:
区别:
在继承thread类中:
1.
2.
在建立runnable接口中:
1.
2
测试结果相同: