1

I want to use timer in my game, but I don't know where should I put (or how to develop it) a code, that will update text every second.

At this moment I'm using onMouseMoved event handler to update the text but I want it to run without being dependent on a mouse

Main class:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        Text textTimer = new Text(x,y,"string");
        numberHandler.timer.scheduleAtFixedRate(numberHandler.startCounting, 0, 1000);
        ...
    }
}

Class with a timer:

public class numberHandler {
    int timePassed = 0;
    Timer timer = new Timer();
    TimerTask startCounting = new TimerTask() {
        @Override
        public void run() {
            timePassed++;
        }
    };
}
dzixper
  • 21
  • 3
  • Possible duplicate of [JavaFX periodic background task](https://stackoverflow.com/questions/9966136/javafx-periodic-background-task) – SedJ601 Oct 10 '19 at 14:12

1 Answers1

2

You could Use The Animation timer from JFX


public class NumberHandler{
   private StringProperty text = new SimpleStringProperty();
   private LongProperty elapsedTime = new SimpleLongProperty(0);
   private IntegerProperty seconds = new SimpleIntegerProperty(0);
   private AnimationTimer timer = new AnimationTimer() {

            @Override
            public void handle(long now) {
                //now is time in Nano seconds
                // to get one second devide by 10^9 
                if((now-elapsedTime.get())/1_000_000_000L > 1){
                  secongs.set(seconds.get()+1);
                  text.set("Time: " + secounds);

                }
            }
        };

      public StringProperty getText(){
         return text;
      }
      public void startTimer(){
         timer.play();
      }

}

In the UI you should Bind the Text.

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        NumberHandler numberHandler = new NumberHander();
        Text textTimer = new Text(x,y,"string");
        textTimer.textproperty.bind(humberHandler.getText());
        numberHandler.startTimer();
    }
}

This is just an approach.

Luxusproblem
  • 1,913
  • 11
  • 23
  • 1
    that doesn't compile, please be thorough with code in answers! (and just in case: no, don't make the fields static :) – kleopatra Oct 10 '19 at 14:37