title: JavaFX stopwatch timer
body: <p>This is a class for a simple stopwatch for JavaFX, style the Label object as desired</p>
  
  <pre><code>package aaa;
  
  import java.text.SimpleDateFormat;
  import java.util.Date;
  import javafx.beans.property.SimpleStringProperty;
  
  /**
   *
   * @author D07114915
   */
  public class KTimer extends Thread {
  
  private Thread thread = null;
  private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss:S");
  private String[] split;
  private SimpleStringProperty min, sec, millis, sspTime;
  private long time;
  
  public static void main(String[] args) {
      KTimer t = new KTimer();
      t.startTimer(00);
  }
  
  public KTimer() {
      min = new SimpleStringProperty("00");
      sec = new SimpleStringProperty("00");
      millis = new SimpleStringProperty("00");
      sspTime = new SimpleStringProperty("00:00:00");
  }
  
  public void startTimer(long time) {
      this.time = time;
      thread = new Thread(this);
      thread.setPriority(Thread.MIN_PRIORITY);
      thread.start();
  }
  
  public void stopTimer(long time) {
      if (thread != null) {
          thread.interrupt();
      }
      this.time = time;
      setTime(time);
  }
  
  public void setTime(long time) {
      this.time = time;
      split = sdf.format(new Date(time)).split(":");
      min.set(split[0]);
      sec.set(split[1]);
  
      if (split[2].length() == 1) {
          split[2] = "0" + split[2];
      }
      millis.set(split[2].substring(0, 2));
  
      sspTime.set(min.get() + ":" + sec.get() + ":" + millis.get());
  }
  
  public long getTime() {
      return time;
  }
  
  public SimpleStringProperty getSspTime() {
      return sspTime;
  }
  
  @Override
  public void run() {
      try {
          while (!thread.isInterrupted()) {
              setTime(time);
              sleep(10);
              time = time + 10;
          }
      } catch (Exception e) {
      }
  
  }
  }//end of class
  </code></pre>
  
  <p>Now just get a listener on the property for your GUI</p>
  
  <p>Add vars</p>
  
  <pre><code>    KTimer ktimer;
      Label timeLabel;
  </code></pre>
  
  <p>in your class initialize the vars </p>
  
  <pre><code>    //Clock
      ktimer = new KTimer();
      timeLabel = new Label(ktimer.getSspTime().get());
      ktimer.getSspTime().addListener(new InvalidationListener() {
  
          @Override
          public void invalidated(Observable observable) {
              timeLabel.setText(ktimer.getSspTime().get());
          }
      });
  </code></pre>
  
  <p>then call the method to start and stop wherever you need to</p>
  
  <p>Stop and reset is</p>
  
  <pre><code>                ktimer.stopTimer(0);
  </code></pre>
  
  <p>Start and Pause timer is </p>
  
  <pre><code>               ktimer.startTimer(ktimer.getTime());
  </code></pre>
  
  <p>Any improvements appreciated as the class is a bit CPU hungry..., but you can adjust the run thread and setTime(time) functions to suit the application</p>