タイマーの機能を提供するクラス
実行する処理をスケジューリングすることで指定の処理を定期的に呼び出す
・TimerTaskクラス
Timerで実行する処理のタスク
これを継承したクラスを新たに用意し、その中にrunメソッドとしてタイマーによる処理を用意する
①TimerTaskを継承したクラスを用意し、そこにタイマーで実行する処理をrunメソッドとして用意する
class クラス extends TimerTask{
public void run(){
タイマーで実行する処理
}
}
②タイマーを開始する場合は、TimerとTimerTask継承クラスのインスタンスをnewで作成する(Timer/TimerTaskのコンストラクタ)
Timer = new Timer();
TimerTask = new TimerTask;
③「schedule」メソッドを使ってTimerTask継承クラスのインスタンスをスケジューリングする(スケジューリングのメソッド)
Timer.schedule(TimerTask,遅延時間);
Timer.schedule(TimerTask,Date);
Timer.schedule(TimerTask,遅延時間,繰り返し間隔);
Timer.schedule(TimerTask,Date,繰り返し間隔);
遅延時間:スタートするまでの遅延時間(ミリ秒単位のlong型)
繰り返し間隔:呼び出す間隔(ミリ秒単位のlong型)
Date:開始する時刻を示すDateインスタンス
④指定されたスケジュールにTimerTask継承クラスのrunメソッドが実行される
途中でタイマーを停止する場合はcancelメソッドを呼び出す
Timer.cancel();
例.
public class TimerApp extends Frame implements ActionListener{
Button b1;
Panel p1;
int num = 1;
public static void main(String[] args) {
new TimerApp();
}
public TimerApp(){
this.setSize(300,200);
p1 = new Panel();
this.add(p1,BorderLayout.CENTER);
b1 = new Button("Click");
b1.addActionListener(this);
this.add(b1,BorderLayout.SOUTH);
this.setVisible(true);
}
public void actionPerformed(ActionEvent ev){
p1.setLayout(new GridLayout(num++,1));
Random rnd = new Random();
TimeLabel tl1 = new TimeLabel();
tl1.end = rnd.nextInt(90)+10;
tl1.delay = rnd.nextInt(2500)+500;
p1.add(tl1);
p1.doLayout();
}
}
class TimeLabel extends Label{
int num = 0;
int end = 100;
int delay = 1000;
boolean kiss_of_death = false;
TimeLabel(){
this.setText("count: 0");
this.setFont(new Font("SansSerif",Font.BOLD,18));
this.setForeground(Color.BLUE);
Timer t = new Timer();
t.schedule(new TimeLabelTask(),0,delay);
}
class TimeLabelTask extends TimerTask{
public void run(){
setText("count: "+ num++);
if(num == end){
num = 0;
}
}
}
}
0 件のコメント:
コメントを投稿