argius note

プログラミング関連

即興:ストップウォッチ

Java5.0以上。即興で1から書いてみる。SPLIT機能の無い簡単なもの。基本的に、使い捨てコードです。

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;

public class StopWatch extends JFrame implements Runnable {

    private JTextField tView;
    private boolean running;
    private long startTime;

    public StopWatch() {
        setTitle("StopWatch");
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.tView = new JTextField();
        JButton bStart = new JButton("START");
        bStart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                running = true;
                startTime = System.currentTimeMillis();
                Thread thread = new Thread(StopWatch.this);
                thread.start();
            }
        });
        JPanel panel = new JPanel(new FlowLayout());
        panel.add(bStart);
        JButton bStop = new JButton("STOP");
        bStop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                running = false;
            }
        });
        panel.add(bStop);
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(tView, BorderLayout.CENTER);
        contentPane.add(panel, BorderLayout.SOUTH);
        pack();
    }

    public void run() {
        final int rH = 60 * 60 * 1000;
        final int rM = 60 * 1000;
        final int rS = 1000;
        while (running) {
            long now = System.currentTimeMillis() - startTime;
            int hour = (int)(now / rH);
            now -= hour * rH;
            int minute = (int)(now / rM);
            now -= minute * rM;
            int second = (int)(now / rS);
            int millisec = (int)(now % rS);
            StringBuffer buffer = new StringBuffer();
            Formatter formatter = new Formatter(buffer);
            formatter.format("%4d:%02d:%02d:%03d",
                             hour,
                             minute,
                             second,
                             millisec);
            tView.setText(buffer.toString());
            try {
                Thread.sleep(50);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new StopWatch();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

}