javax.swingパッケージのTimerオブジェクトを使用してストップウォッチを作成しました。インスタンス化したときに、遅延を100ミリ秒に設定しましたが、タイマーは秒ではなくミリ秒で実行されているようです。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class StopWatch extends JApplet
{
private JPanel timePanel;
private JPanel buttonPanel;
private JTextField time;
private int seconds = 0;
boolean running = false;
private Timer timer;
public void init()
{
buildTimePanel();
buildButtonPanel();
setLayout(new GridLayout(3, 1));
add(timePanel);
add(buttonPanel);
}
private void buildTimePanel()
{
timePanel = new JPanel();
JLabel message1 =
new JLabel("Seconds: ");
time = new JTextField(10);
time.setEditable(false);
timePanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
timePanel.add(message1);
timePanel.add(time);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
startButton.addActionListener(new StartButtonListner());
stopButton.addActionListener(new StopButtonListner());
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
}
private class StartButtonListner implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(running == false){
running = true;
if(timer == null){
timer = new Timer(100, new TimeActionListner());
timer.start();
} else {
timer.start();
}
}
}
}
private class StopButtonListner implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(running == true){
running = false;
timer.stop();
}
}
}
private class TimeActionListner implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
time.setText(Integer.toString(seconds));
seconds++;
}
}
}