Using timer to count as a stopwatch in Java Applet

Julian Barrie picture Julian Barrie · Jun 15, 2012 · Viewed 7.5k times · Source

I'm wanting to create a stopwatch so to speak in order to score my game. Lets say I have a variable: int sec = 0. When the game starts I want a g.drawString to draw the time to the applet. So for example each second, sec will increment by 1.

How do I go about making it g.drawString(Integer.toString(sec), 40, 400) increment by 1 and draw each second?

Thanks.

EDIT:

I've figured out how to increment it and print it to the screen by using ActionListener and putting g.drawString in there but it prints ontop of each other. If I put g.drawString into the paint method and only increment sec by 1 in the ActionListener there is a a flicker. Should I use Double Buffering? If so how do I go about doing this?

Answer

Naveen Kumar Yadav picture Naveen Kumar Yadav · Jun 15, 2012
import java.awt.event.*;
import javax.swing.*;

public class StopWatch extends JLabel
            implements MouseListener, ActionListener {

   private long startTime;   // Start time of stopwatch.
                             //   (Time is measured in milliseconds.)

   private boolean running;  // True when the stopwatch is running.

   private Timer timer;  // A timer that will generate events
                         // while the stopwatch is running

   public StopWatch() {
         // Constructor.
      super("  Click to start timer.  ", JLabel.CENTER);
      addMouseListener(this);
   }

   public void actionPerformed(ActionEvent evt) {
          // This will be called when an event from the
          // timer is received.  It just sets the stopwatch
          // to show the amount of time that it has been running.
          // Time is rounded down to the nearest second.
       long time = (System.currentTimeMillis() - startTime) / 1000;
       setText("Running:  " + time + " seconds");
   }

   public void mousePressed(MouseEvent evt) {
          // React when user presses the mouse by
          // starting or stopping the stopwatch.  Also start
          // or stop the timer.
      if (running == false) {
            // Record the time and start the stopwatch.
         running = true;
         startTime = evt.getWhen();  // Time when mouse was clicked.
         setText("Running:  0 seconds");
         if (timer == null) {
            timer = new Timer(100,this);
            timer.start();
         }
         else
            timer.restart();
      }
      else {
            // Stop the stopwatch.  Compute the elapsed time since the
            // stopwatch was started and display it.
         timer.stop();
         running = false;
         long endTime = evt.getWhen();
         double seconds = (endTime - startTime) / 1000.0;
         setText("Time: " + seconds + " sec.");
      }
   }

   public void mouseReleased(MouseEvent evt) { }
   public void mouseClicked(MouseEvent evt) { }
   public void mouseEntered(MouseEvent evt) { }
   public void mouseExited(MouseEvent evt) { }

}  // end StopWatchRunner

A small applet to test the component:

/*
   A trivial applet that tests the StopWatchRunner component.
   The applet just creates and shows a StopWatchRunner.
*/


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

public class Test1 extends JApplet {

   public void init() {

      StopWatch watch = new StopWatch();
      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);

   }

}