A 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….”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | /******************************************************* * MYCPLUS Sample Code - https://www.mycplus.com * * * * This code is made available as a service to our * * visitors and is provided strictly for the * * purpose of illustration. * * * * Please direct all inquiries to saqib at mycplus.com * *******************************************************/ 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 boolean running; // True when the timer is running. public StopWatch() { // Constructor. super(" Click to start timer. ", JLabel.CENTER); addMouseListener(this); } public void mousePressed(MouseEvent evt) { // React when user presses the mouse by // starting or stoping the timer. if (running == false) { // Record the time and start the timer. running = true; startTime = evt.getWhen(); // Time when mouse was clicked. setText("Timing...."); } 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) { } } // end StopWatch |