How to update the label box every 2 seconds in java fx?

前端 未结 3 612
故里飘歌
故里飘歌 2020-11-27 19:58

I\'m trying to simulate a basic thermostat in an application GUI.

I want to update a label box value every 2 secs with the new temperature value.

For example

3条回答
  •  一整个雨季
    2020-11-27 20:27

    To solve your task using Timer you need to implement TimerTask with your code and use Timer#scheduleAtFixedRate method to run that code repeatedly:

    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):

    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#runLater method instead of SwingUtilities

提交回复
热议问题