How can I use a timer to pause a program for a second before doing something in JavaFX?

安稳与你 提交于 2019-12-13 04:11:56

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/49611162/how-can-i-use-a-timer-to-pause-a-program-for-a-second-before-doing-something-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!