2011-04-29

2011/04/29

import javax.swing.Timer;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class TimerDemo implements ActionListener {
  Timer t = new Timer(1000,this);
static  JLabel tf1=new JLabel();

  TimerDemo() {
    t.start();
    }

  public static void main(String args[]) {
    TimerDemo td = new TimerDemo();
    // create a dummy frame to keep the JVM running
    //  (for demonstation purpose)
    java.awt.Frame dummy = new java.awt.Frame();


dummy.setSize(300,225);
dummy.add(tf1);
    dummy.setVisible(true);
    }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == t) {

       tf1.setText("\007Being ticked " + Calendar.getInstance().getTime());
      System.out.println
        ("\007Being ticked " + Calendar.getInstance().getTime());
      }
    }
}






=================================================

import java.util.Timer;
import java.util.TimerTask;


public class ToDo  {
  Timer timer;

  public ToDo ( int seconds )   {
    timer = new Timer (  ) ;
    timer.schedule ( new ToDoTask (  ) , seconds*1000 ) ;

  }


  class ToDoTask extends TimerTask  {
    public void run (  )   {

System.out.println ( "OK, It's time to do something!" ) ;
timer.cancel (  ) ; //Terminate the thread
    }


  }


  public static void main ( String args [  ]  )   {
    System.out.println ( "Schedule something to do in 5 seconds." ) ;
    new ToDo ( 5 ) ;
    System.out.println ( "Waiting." ) ;
 TimerDemo t1=new TimerDemo();
  }
}

沒有留言:

張貼留言