Stopwatch

We all know what is a stopwatch and the purpose for which it is used. So, I have made a program which imitates the working of a stopwatch. So, let's go directly to the code.

Explaining the code:-

To make this program I have used the Timer class which is included in javax.swing.Timer package. So, I have imported this package.

import javax.swing.Timer;

I have declared three global variables to control the three hands of clock i.e hour, minute and second hands.

int sec=0;
int min =0;
int hrs=0;

Then I have declared the variable of Timer class. The Timer class has the constructor in which we have to provide two parameters. The first parameter is the milliseconds ( 1000 milliseconds = 1 seconds ) and the second parameter is the object of ActionListener in which we give the definition of actionPerformed(ActionEvent e) method. This definition is the code which is executed after every given millisecond in the first parameter of the constructor.

Timer t = new Timer(1000,new ActionListener(){

public void actionPerformed(ActionEvent e){
    sec++;

    if(sec == 60){
        sec = 0;
        min++;
    }
    if(min == 60){
        min =0;
        hrs++;
    }

    if(sec < 10){
        seclbl.setText("0"+sec);
    }else
        seclbl.setText(""+sec);
    if(min < 10){
        minlbl.setText("0"+min);
    }else
        minlbl.setText(""+min);
    if(hrs < 10){
        hrslbl.setText("0"+hrs);
    }else
        hrslbl.setText(""+hrs);

}

});

Then we have three buttons which work according to the names of button suggest.

Start Button

t.start();

stopwatch start

Stop button

t.stop();

stopwatch stop

Reset button

t.stop();
sec=0;
min=0;
hrs=0;

hrslbl.setText("0"+hrs);     // hrslbl is the name of the hours label
minlbl.setText("0"+min);     // minlbl is the name of the minutes label
seclbl.setText("0"+sec);     // seclbl is the name of the seconds label

stopwatch reset

Project Content:- Download Here

The following two tabs change content below.

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...