Interactive Java Stopwatch Component

Interactive Java Stopwatch Component

The StopWatch class introduces a versatile stopwatch component with enhanced functionality in Java. Extending JLabel and implementing the MouseListener interface, this interactive component not only measures elapsed time but also dynamically updates to display the current time in the format “Hours:Minutes:Seconds:Milliseconds” while running. Clicking on the stopwatch initiates the timer, and subsequent clicks allow users to stop the timer, showing the precise elapsed time. A unique feature includes continuous real-time updates on the label, providing a seamless display of the ongoing time.

This implementation showcases the power of Swing components, event-driven programming, and the use of a javax.swing.Timer to create an engaging and responsive stopwatch experience within a graphical user interface.

import java.awt.event.*;
import javax.swing.*;

public class StopWatch extends JLabel implements MouseListener {

    private long startTime;   // Start time of timer.
                              //   (Time is measured in milliseconds.)

    private Timer timer;      // Timer for updating the label.
    private boolean running;  // True when the timer is running.
    private int clickCount;   // Count of mouse clicks.

    public StopWatch() {
        // Constructor.
        super("Stopwatch", JLabel.CENTER);
        addMouseListener(this);

        // Create a timer to update the label every 100 milliseconds.
        timer = new Timer(100, e -> updateLabel());
    }

    private void updateLabel() {
        // Update the label with the current elapsed time.
        long currentTime = System.currentTimeMillis();
        long elapsedTime = currentTime - startTime;

        // Format the elapsed time in Hours:Minutes:Seconds:Milliseconds
        long hours = (elapsedTime / 3600000) % 24;
        long minutes = (elapsedTime / 60000) % 60;
        long seconds = (elapsedTime / 1000) % 60;
        long milliseconds = elapsedTime % 1000;

        setText(String.format("%02d:%02d:%02d:%03d", hours, minutes, seconds, milliseconds));
    }

    public void mousePressed(MouseEvent evt) {
        // React when the user presses the mouse by starting,
        // stopping, or restarting the timer.

        clickCount++;

        if (clickCount == 1) {
            // Start the timer and record the start time.
            running = true;
            startTime = System.currentTimeMillis();
            timer.start();
        } else if (clickCount == 2) {
            // Stop the timer. Update the label once more.
            running = false;
            timer.stop();
            updateLabel();
        } else {
            // Reset the click count and stop the timer.
            clickCount = 0;
            running = false;
            timer.stop();
            setText("Stopwatch");
        }
    }

    public void mouseReleased(MouseEvent evt) {
    }

    public void mouseClicked(MouseEvent evt) {
    }

    public void mouseEntered(MouseEvent evt) {
    }

    public void mouseExited(MouseEvent evt) {
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("StopWatch Application");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            StopWatch stopWatch = new StopWatch();
            frame.getContentPane().add(stopWatch);

            frame.setSize(300, 200);
            frame.setVisible(true);
        });
    }
}

The label continuously updates with the current elapsed time while the stopwatch is running. The javax.swing.Timer triggers the updateLabel() method every 100 milliseconds to refresh the displayed time.

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post