7 Sept 2012

Stopwatch in java source code


import java.awt.event.*;
import javax.swing.*;

public class StopWatch2 extends JLabel
            implements KeyListener, ActionListener {

   private long startTime;                           

   private boolean running;  
   private Timer timer;  
   public StopWatch2() {
             super("  Press S  ", JLabel.CENTER);
      addKeyListener(this);
   }

   public void actionPerformed(ActionEvent evt) {

       long time = (System.currentTimeMillis() - startTime) / 1000;
       setText(Long.toString(time));
   }

   public void keyPressed(KeyEvent e) {

          int keyCode=e.getKeyCode();
      if (keyCode==KeyEvent.VK_S) {
                     running = true;
         startTime = e.getWhen(); 
         setText("Running:  0 seconds");
         if (timer == null) {
            timer = new Timer(100,this);
            timer.start();
         }
         else
            timer.restart();
      }
      if(keyCode==KeyEvent.VK_P)
      {

         timer.stop();
         running = false;
         long endTime = e.getWhen();
         double seconds = (endTime - startTime) / 1000.0;
         setText("Time: " + seconds + " sec.");
      }
   }
   public void keyTyped(KeyEvent e)
   {}
   public void keyReleased(KeyEvent e)
   {}

} 


import java.awt.*;
import javax.swing.*;

public class Test2 extends JApplet {

   public void init() {

      StopWatch2 watch = new StopWatch2();
      watch.setFont( new Font("SansSerif", Font.BOLD, 24) );
      watch.setBackground(Color.white);
      watch.setForeground( new Color(180,0,0) );
      watch.setOpaque(true);
      getContentPane().add(watch, BorderLayout.CENTER);

   }

}

0 comments:

Post a Comment