編集部 All About
Javaプログラミング関連情報
更新日:2006年04月11日
一定時間が経過したら自動的に処理を実行する。そういうとき、どうします? そういう処理を簡単に実現するのがJavaの『タイマー(Timer)』なのです。
![]() |
| Timerを使うと、指定の時間が経過すると用意されたTimerTaskの処理を実行することができる。 |
import java.awt.*;
import java.text.*;
import java.util.*;
import java.util.Timer;
import javax.swing.*;
public class Sample extends JFrame {
JLabel label;
public static void main(String[] args) {
new Sample();
}
public Sample() {
this.setSize(200,100);
this.setLayout(new BorderLayout());
label = new JLabel();
label.setFont(new Font("Dialog",
Font.BOLD,24));
this.getContentPane().add(label,
BorderLayout.CENTER);
Timer t = new Timer();
t.schedule(new MyTimer(),0,500);
this.setVisible(true);
}
class MyTimer extends TimerTask {
boolean f = false;
public void run(){
String delim = f ? ":" : " ";
f = !f;
String str = "hh" + delim +
"mm" + delim + "ss";
SimpleDateFormat sf =
new SimpleDateFormat(str);
GregorianCalendar cal =
new GregorianCalendar();
label.setText(sf.format(cal.getTime()));
}
}
}
![]() |
| 実行すると、JLabelに現在の時刻がリアルタイムに表示される。 |
(執筆者:掌田 津耶乃)
この記事の担当ガイド

編集部 All About