Stop Watch in Java with GUI

In this program we will learn how to make a stop watch in Java with GUI. The stop watch calculate the Nanoseconds, seconds , mints and hours. The GUI provide the start button, stop button and terminate program button. 

Source Code

import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;

public class MainCalss {
  
  //Note: Typically the main method will be in a
  //separate class. As this is a simple one class
  //example it's all in the one class.
  public static void main(String[] args) {
      
      new MainCalss();
  }
  private volatile boolean running = true;
  public MainCalss()
  {
      JFrame guiFrame = new JFrame();
      
      //make sure the program exits when the frame closes
      guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      guiFrame.setTitle("Stopwatch");
      guiFrame.setSize(300,100);
    
      //This will center the JFrame in the middle of the screen
      guiFrame.setLocationRelativeTo(null);
       
      //The first JPanel contains a JLabel and JCombobox
      final JPanel comboPanel = new JPanel();
      JLabel Lbl = new JLabel("Time(day:hrs:min:sec) : ");
      final JLabel timeLbl = new JLabel("");
      
     comboPanel.add(Lbl);
     comboPanel.add(timeLbl);
        
      final JButton startBut = new JButton( "Start");
      JButton stopBut = new JButton( "Stop");
      JButton reStartBut = new JButton( "Re Start");
      
      //The ActionListener class is used to handle the
      //event that happens when the user clicks the button.
      //As there is not a lot that needs to happen we can 
      //define an anonymous inner class to make the code simpler.
      startBut.addActionListener(new ActionListener()
      {
          public void actionPerformed(ActionEvent event)
          {
           
            new Thread(new Runnable()
          {
              public void run()
              {
                  long start = System.currentTimeMillis();
                  while (running)
                  {
                      long time = System.currentTimeMillis() - start;
                      final long seconds = time / 1000;
                      SwingUtilities.invokeLater(new Runnable() {
                           public void run()
                           {
                           int days = (int) seconds/60/60/24;
                         int hours =(int) (seconds/ 60 / 60)%24;
                         int minutes =(int) (seconds / 60) % 60;
                         int sec =(int) seconds % 60;
                            timeLbl.setText(days+" : "
                             +hours+" : "
                            +minutes+" : "
                            +sec+"");
                           }
                      });
                      try { Thread.sleep(100); } catch(Exception e) {}
                  }
              }
          }).start();
           
          }
      });
      stopBut.addActionListener(new ActionListener()
      {
          public void actionPerformed(ActionEvent event)
          {
           try { pauseThread(); } catch(Exception e) {System.out.print("Error: "+e+"\n");}
           
          }
      });
      reStartBut.addActionListener(new ActionListener()
      {
          public void actionPerformed(ActionEvent event)
          {
           try { 
            resumeThread();
            click(startBut,100);
           } catch(Exception e) {System.out.print("Error: "+e+"\n");}
           
          }
      });
      
      //The JFrame uses the BorderLayout layout manager.
      //Put the two JPanels and JButton in different areas.
      guiFrame.add(comboPanel, BorderLayout.NORTH);
      guiFrame.add(startBut,BorderLayout.EAST);
      guiFrame.add(stopBut,BorderLayout.WEST);
      guiFrame.add(reStartBut,BorderLayout.CENTER);
      
      //make sure the JFrame is visible
      guiFrame.setVisible(true);
  }
  public void pauseThread() throws InterruptedException
  {
      running = false;
  }

  public void resumeThread()
  {
      running = true;
  }

  //Simulation of Programmatically clicking a GUI button in Java Swing
  public void click(AbstractButton button, int millis) throws AWTException
  {
      Point p = button.getLocationOnScreen();
      Robot r = new Robot();
      r.mouseMove(p.x + button.getWidth() / 2, p.y + button.getHeight() / 2);
      r.mousePress(InputEvent.BUTTON1_MASK);
      try { Thread.sleep(millis); } catch (Exception e) {}
      r.mouseRelease(InputEvent.BUTTON1_MASK);
  }
}

Output of the Program

Stop Watch in Java with GUI
Stop Watch in Java with GUI

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment