java JavaFX每秒显示时间和刷新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38566638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:32:32  来源:igfitidea点击:

JavaFX Displaying Time and Refresh in Every Second

javatimejavafxtimer

提问by MaraSimo

Hello I would like to ask for any advice on this problem.

您好,我想就这个问题寻求任何建议。

I would like to display current time in HH:MM:SS format (refreshing every second) in label or whatever component that is good for it.

我想在标签或任何适合它的组件中以 HH:MM:SS 格式(每秒刷新一次)显示当前时间。

Any advice?

有什么建议吗?

EDIT: Someone asked for a code.. so I put it here for better description of the problem. "I have no code for that time What I'm trying to achieve is simple GUI diary and in one of the labels I would like to display time remaining until the closest event and in the other label I want to display like clocks that refreshes every second. I need it to get remaining time working. All I can think of is creating new thread that will do it and refreshes the clock, but I am not that advanced to use multithreading in JavaFX . So I was wondering if anyone can advice me with something less complicated than multithreading (I dont know how to implement that thread into JavaFX components)"

编辑:有人要求提供代码..所以我把它放在这里是为了更好地描述问题。“我没有这段时间的代码我想要实现的是简单的 GUI 日记,在其中一个标签中,我想显示距离最近事件的剩余时间,而在另一个标签中,我想像时钟一样显示每个第二。我需要它来让剩余时间工作。我所能想到的就是创建新线程来完成它并刷新时钟,但我在 JavaFX 中使用多线程并不是那么先进。所以我想知道是否有人可以建议我比多线程更简单的东西(我不知道如何将该线程实现到 JavaFX 组件中)”

回答by Andrey M

Version with Timeline:

带时间轴的版本:

long endTime = ...;
Label timeLabel = new Label();
DateFormat timeFormat = new SimpleDateFormat( "HH:mm:ss" );
final Timeline timeline = new Timeline(
    new KeyFrame(
        Duration.millis( 500 ),
        event -> {
            final long diff = endTime - System.currentTimeMillis();
            if ( diff < 0 ) {
            //  timeLabel.setText( "00:00:00" );
                timeLabel.setText( timeFormat.format( 0 ) );
            } else {
                timeLabel.setText( timeFormat.format( diff ) );
            }
        }
    )
);
timeline.setCycleCount( Animation.INDEFINITE );
timeline.play();

回答by Mjachowdhury

One might find helpful how to print date and time for javaFx.

人们可能会发现如何为 javaFx 打印日期和时间很有帮助。

final Label clock = new Label();
final DateFormat format = DateFormat.getInstance();
final Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), 
new EventHandler() 
{
@Override  
    public void handle(ActionEvent event) 
    {
      final Calendar cal = Calendar.getInstance();
      clock.setText(format.format(cal.getTime());
    }
});

timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();

回答by Baftjar Tabaku

   Label main_clock_lb = new Label();
    Thread timerThread = new Thread(() -> {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        while (true) {
            try {
                Thread.sleep(1000); //1 second
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            final String time = simpleDateFormat.format(new Date());
            Platform.runLater(() -> {
                main_clock_lb.setText(time);
            });
        }
    });   timerThread.start();//start the thread and its ok

回答by Abhishek T.

To solve your task using Timer you need to implement TimerTaskwith your code and use Timer#scheduleAtFixedRatemethod to run that code repeatedly:

要使用 Timer 解决您的任务,您需要TimerTask使用代码实现并使用Timer#scheduleAtFixedRate方法重复运行该代码:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        System.out.print("I would be called every 2 seconds");
    }
}, 0, 2000);

Also note that calling any UI operations must be done on Swing UI thread (or FX UI thread if you are using JavaFX):

另请注意,调用任何 UI 操作都必须在 Swing UI 线程(或 FX UI 线程,如果您使用的是 JavaFX)上完成:

   private int i = 0;
   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    jTextField1.setText(Integer.toString(i++));
                }
            });
        }
    }, 0, 2000);
}

In case of JavaFX you need to update FX controls on "FX UI thread" instead of Swing one. To achieve that use javafx.application.Platform#runLatermethod instead of SwingUtilities

在 JavaFX 的情况下,您需要在“FX UI 线程”而不是 Swing 上更新 FX 控件。要实现该使用javafx.application.Platform#runLater方法而不是 SwingUtilities

回答by Sunil Dixit

    final Label clock = new Label();
    final DateFormat format = DateFormat.getInstance();
    final Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1),
            new EventHandler<ActionEvent>()
            {
                @Override
                public void handle(ActionEvent event)
                {
                    final Calendar cal = Calendar.getInstance();
                    clock.setText(format.format(cal.getTime()));
                }
            }));

    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();