FahmidasClassroom

Learn by easy steps

Stopwatch2

The way to create a stopwatch using Java has been shown in this tutorial. Here, the JFrame form has been used to create the interface of the stopwatch. Follow the steps given below to create the application.
Steps:
01. Create a new Java application named stopwatch.
02. Create a JFrame named StopWatch2 and follow the video to design the interface for the stopwatch using design tool.
03. Write the following code in the constructor of the class to set the Form title and size.

setTitle("Stopwatch Application");
setSize(300, 100);

05. Declare the following class variables.

long startTime;
long stopTime;
double elapsedTime;

06. Declare method for the start button.

private void startButtonActionPerformed(ActionEvent e)
{
     //click of start timing button
     startTime = System.currentTimeMillis();
     startTextField.setText(String.valueOf(startTime));
     stopTextField.setText("");
     elapsedTextField.setText("");
}

07. Declare method for the stop button.

private void stopButtonActionPerformed(ActionEvent e)
{
      // click of stop timing button
      stopTime = System.currentTimeMillis();
      stopTextField.setText(String.valueOf(stopTime));
      elapsedTime = (stopTime - startTime) / 1000.0;
      elapsedTextField.setText(String.valueOf(elapsedTime));
}

08. Declare method for the exit button.

private void exitButtonActionPerformed(ActionEvent e)
{
      System.exit(0);
}

09. Add code to call the methods of the buttons.

startButton.addActionListener(this::startButtonActionPerformed);
stopButton.addActionListener(this::stopButtonActionPerformed);
exitButton.addActionListener(this::exitButtonActionPerformed);

10. Compile the source code and run the application.
***The source code is taken from “Learn Java GUI Applications” book.