Stopwatch project in Java with full source code

The StopWatchLabel component from section 12.4.5 in the textbook displays the text "Timing..." when the stopwatch is running. It would be nice if it displayed the elapsed time since the stop watch was started. For that, you need to create a Timer (see section 6.5.1 in the textbook.) Add a Timer to the original source code, in the code directory, to drive the display of the elapsed time in seconds. Create the timer in the mousePressed() routine when the stop watch is started. Stop the timer in the mousePressed() routine when the stop watch is stopped. The elapsed time won't be very accurate anyway, so just show the integral number of seconds. You only need to set the text a few times per second. For the Timer method, use a delay of 200 milliseconds for the timer. Here is an applet that tests one possible solution to this exercise:


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

* A custom component that acts as a simple stop-watch. When the user clicks
* on it, this componet starts timing. When the user clicks again,
* it displays the time between the two clicks. Clicking a third time
* starts another timer, etc. While it is timing, the label just
* displays the message "Timing....".
public class StopWatchLabel extends JLabel implements MouseListener {

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

private boolean running; // True when the timer is running.

* Constructor sets initial text on the label to
* "Click to start timer." and sets up a mouse listener
* so the label can respond to clicks.
public StopWatchLabel() {
super(" Click to start timer. ", JLabel.CENTER);

* Tells whether the timer is currently running.
public boolean isRunning() {
return running;

* React when the user presses the mouse by starting
* or stopping the timer and changing the text that
* is shown on the label.
public void mousePressed(MouseEvent evt) {
if (running == false) {
// Record the time and start the timer.
running = true;
startTime = evt.getWhen(); // Time when mouse was clicked.
else {
// Stop the timer. Compute the elapsed time since the
// timer was started and display it.
running = false;
long endTime = evt.getWhen();
double seconds = (endTime - startTime) / 1000.0;
setText("Time: " + seconds + " sec.");

public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }


Powered by