在JavaFX中执行某些操作之前,如何使用计时器将程序暂停一秒钟? [英] How can I use a timer to pause a program for a second before doing something in JavaFX?

查看:125
本文介绍了在JavaFX中执行某些操作之前,如何使用计时器将程序暂停一秒钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java Swing中,我使用了Swing计时器(而不是util计时器)来执行此操作.代码如下:

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

但是我听说最好不要在JavaFX程序中使用Swing导入.我已经搜索了很多东西,但仍然找不到如何在JavaFX中进行此操作.

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.

有来自java.util的Timer.但是我无法弄清楚如何使用它来设置时间和应该在该时间之后完成的任务.

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.

一些相关信息:

1)我正在开发一个GUI程序.这在后台运行.通常,我会在暂停后使用它来播放音频.

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)我是JavaFX的新手.

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

非常感谢.

推荐答案

对于JavaFX操作,请考虑使用时间轴:

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

这篇关于在JavaFX中执行某些操作之前,如何使用计时器将程序暂停一秒钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆