0

In Java Swing I used the Swing Timer (not util Timer) to do it. The code looks like this:

Timer timer = new Timer(1000, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            // "Hello there" is printed out after the 1000 miliseconds
            System.out.Println("Hello there");
        } catch (Exception e1) {
        }
    }
});
timer.setRepeats(false);
timer.start();

But I heard it's best not to use Swing imports in JavaFX programs. I've searched so much but I still can't find out how I can do this in JavaFX.

There's the Timer from java.util. But I'm not able to figure out how to do use it to set a time and task that should be done after the time.

Some relevant info:

1) I'm developing a GUI program. This runs in the background. Mostly I'd be using it to play an audio after a pause.

2) I'm very much a newbie to JavaFX.

Thanks a lot.

Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
Dan
  • 95
  • 11
  • Like you mentioned you can just use java.util. https://stackoverflow.com/questions/2258066/java-run-a-function-after-a-specific-number-of-seconds – Eralp Sahin Apr 02 '18 at 12:24
  • 3
    Use any suitable kind of scheduling the task and use `Platform.runLater` if you need to do something on the JavaFX application thread. Using Swing-Timer is not a good idea since it's designed to work with the awt event thread != JavaFX application thread. – fabian Apr 02 '18 at 12:33
  • 3
    Use a `PauseTransition` or a [`Timeline`](https://stackoverflow.com/a/9966213/2189127). – James_D Apr 02 '18 at 12:41
  • @EralpŞahin, Thank you. The link you had provided showed me I'd have to call the cancel method to make sure the thread doesn't leak. (Not that I understand what thread leaking exactly is!) Thank you. :) – Dan Apr 02 '18 at 19:04
  • @fabian Thanks. I'll make sure I don't mix Swing and FX, – Dan Apr 02 '18 at 19:05

1 Answers1

0

For JavaFX operations, consider using Timeline:

Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), e -> System.out.println("Printed after 1 second from FX thread")));
timeline.play();
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
  • 1
    Be aware if you are updating a `Label`, you will need to wrap it in a `Platform.runLater()` – Hypnic Jerk Apr 02 '18 at 16:22
  • Thanks! It works beautifully! I don't think I'd get a better answer. I'll accept your answer after waiting a few hours. I followed a link given above. Someone there had mentioned that you may leak threads sometimes if it's used. It was said we can prevent that by calling the cancel method. So I added the method after the 5th line of your model code. (After the sys out). It worked fine. I can leave it like that right? – Dan Apr 02 '18 at 19:02
  • @Dan you can write whatever you want to run inside the `run()` method. – Miss Chanandler Bong Apr 02 '18 at 19:16
  • @M.S., Thanks a lot. – Dan Apr 03 '18 at 02:32