0% found this document useful (0 votes)
56 views8 pages

Java Stopwatch Applet Example

This Java program creates a stopwatch applet with start, stop, and reset buttons. The applet uses threads to continuously update the displayed time. When start is clicked, a thread runs that increments the milliseconds, seconds, minutes, and hours variables and updates the displayed time label. When stop is clicked, the thread stops running. When reset is clicked, all time variables are reset to initial values of zero. The applet provides a simple example of creating a timer with threads and handling button click events.

Uploaded by

Devendra Mali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views8 pages

Java Stopwatch Applet Example

This Java program creates a stopwatch applet with start, stop, and reset buttons. The applet uses threads to continuously update the displayed time. When start is clicked, a thread runs that increments the milliseconds, seconds, minutes, and hours variables and updates the displayed time label. When stop is clicked, the thread stops running. When reset is clicked, all time variables are reset to initial values of zero. The applet provides a simple example of creating a timer with threads and handling button click events.

Uploaded by

Devendra Mali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Program Code:-

******************Stop Watch******************

import [Link].*;

import [Link].*;

import [Link];

import [Link];

public class Clock extends Applet implements Runnable,ActionListener

//Panel to keep all the buttons and label

Panel p;

Label display;

    //Button

Button start, stop, reset;

//Time

int hour, minute,second,millisecond;

//String to be displayed on the label

String disp;

//State of stopwatch on/off

boolean on;

    //Initialization
public void init()

       //Initially off

       on=false;

           p=new Panel();

       //Setting layout of the panel

       [Link](new GridLayout(4,1,6,10));

          //Initial time 00:00:00:000

       hour=minute=second=millisecond=0;

          //Label

      display =new Label();

      disp="00:00:00:000";

      [Link](disp);

      [Link](display);

         //Start Button

     start=new Button("Start");

     [Link]((ActionListener)this);

       [Link](start);

      //Reset Button

      reset = new Button("Reset");

      [Link]((ActionListener)this);
      [Link](reset);

         //Stop Button

         stop=new Button("Stop");

      [Link]((ActionListener)this);

      [Link](stop);

      add(p);

         //Starting Thread

     new Thread(this,"StopWatch").start();

//Reset Function

//Reset to default value

public void reset()

        try{

               [Link](1);

           }

       catch(Exception e){

            [Link](e);

       }

       hour=minute=second=millisecond=0;

}
//Update function

//Update the timer

public void update()

       millisecond++;

       if(millisecond==1000) {

              millisecond=0;

              second++;

              if(second==60)

              {

                  second=0;

                  minute++;

                 if(minute==60)

                  {

                   minute=0;

                   hour++;

                  }

       }

//Changing Label

public void changeLabel()


{

//Properly formatting the display of the timer

if(hour<10)

         disp="0"+hour+" : ";

else

         disp=hour+" : ";

if(minute<10)

         disp+="0"+minute+" : ";

    else

         disp+=minute+" : ";

if(second<10)

         disp+="0"+second+" : ";

else

        disp+=second+" : ";

    if(millisecond<10)

       disp+="00"+millisecond;

else if (millisecond<100)

       disp+="0"+millisecond;

else

       disp+=millisecond;

   [Link](disp);
}

//[Link] function

public void run()

//while the strength is on

while(on)

    try{

       //pause 1 millisecond

       [Link](1);

      //update the timer

      update();

     //changeLabel

     changeLabel();

catch(InterruptedException e){

     [Link](e);

 }

//actionPerformed
//To listen to the actions on the buttons

public void actionPerformed(ActionEvent e)

//start a thread when start button is clicked

if([Link]()==start)

    //stopwatch is on

    on=true;

    new Thread(this,"StopWatch").start();

    //reset

   if([Link]()==reset)

//stopwatch off

on=false;

reset();

changeLabel();

if([Link]()==stop)

//stopwatch off
on=false;}

**********************Applet Code*********************

<html>

<body>

<applet>

<applet code=”[Link]” width=400 height=600>

</applet>

</body>

</html>

Conclusion:-

    Hence from this project we successfully learn to develop a stop watch using applet by
using Action Listener to handle events. This program contains three buttons Start , Stop and
Reset. When the Start button is placed the timer gets start , when we press the Stop button the
the timer gets stop and when the Reset button is pressed then the timer again starts from its
initial value. 

Common questions

Powered by AI

The 'Clock' applet uses multithreading by starting a new Thread with its Runnable implementation whenever the Start button is pressed. This allows the stopwatch to operate asynchronously from the user interface, updating time every millisecond without freezing the UI and allowing the applet to respond to other actions such as button presses .

The update method is crucial for incrementing time, increasing 'millisecond' by one every millisecond. When milliseconds reach 1000, they reset to zero, and 'second' increments, thus cascading into minutes and hours if applicable. This tiered update process ensures the displayed time remains accurate, simulating a real stopwatch .

The GridLayout(4,1,6,10) arranges the components (Label, three buttons) in four equally sized rows with a vertical and horizontal gap of 6 and 10 pixels respectively. This layout ensures equally distributed spacing, maintaining a clean and organized appearance that enhances usability by preventing clutter and enabling easy user interaction .

Using Thread.sleep(1) may cause inaccuracies in timekeeping due to OS-level scheduling factors that might not honor millisecond precision, potentially leading to drift if the system is under heavy load. This can affect performance by causing time lags or interruptions in updating the time display, undermining the reliability expected from a stopwatch .

The actionPerformed method acts as an event handler for button clicks, using conditional checks to determine which button was pressed (Start, Stop, Reset). This facilitates user interactions by triggering corresponding actions like starting the timer or resetting it, demonstrating how event-driven programming permits dynamic and responsive UI experiences .

The java.applet package provides the necessary classes for applet creation, facilitating embedding within HTML pages for deployment. This package allows the 'Clock' applet to be executed in web browsers supporting applets, integrating seamlessly into web environments while managing lifecycle methods like init and start for execution control .

The applet updates the time display by assembling a formatted string in the changeLabel method, adjusting numerical values with leading zeros for consistency (e.g., '08:05:03:050'). The formatted string is then set as the Label text. This approach maintains a consistent visual timing format, crucial for a stopwatch's readability and utility .

While the 'Clock' applet utilizes encapsulation by grouping timer logic into methods, it could improve by separating UI logic from timer operations into distinct classes, enhancing reusability and maintainability. Introducing interfaces or abstract classes for shared behavior among potential different timer types could further align with object-oriented principles .

The 'Clock' applet manages state transitions using a boolean variable 'on' to control the stopwatch status. When the Start button is clicked, actionPerformed sets 'on' to true, activating the while loop in the run method, which updates the time. The Stop button sets 'on' to false, halting the while loop. The Reset button also sets 'on' to false but additionally calls the reset method to set time values to zero and updates the display via changeLabel .

The GridLayout is used for organizing the Label and buttons (Start, Stop, Reset) in a structured and evenly spaced manner. This choice simplifies the user interface, enhancing accessibility by making controls easy to identify and use, thus providing an efficient user experience critical for real-time applications like a stopwatch .

You might also like