How to update a Label automatically every minute?

1

I'm trying to make an app that checks the price of a product every minute.

In my test code it looks like this:

package sample;

import javafx.stage.Stage;

import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

import static sample.Controller.updateTicker;


public class MyTask{

    public Label helloWorld;

    public void criarTimer(Stage primaryStage) {
        int segundos = 10;
        int segundosParaComecar = 0;
        int segundosParaCapturar = segundos*1000;

        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {

            public void run() {
                helloWorld.setText(updateTicker());
            }
        };        

        timer.schedule(timerTask, segundosParaComecar, segundosParaCapturar);
    }
}

But I'm having the following Error log and I do not know how to resolve:

  

Exception in thread "Timer-0" java.lang.NullPointerException at   sample.MyTask $ 1.run (MyTask.java:23) at   java.util.TimerThread.mainLoop (Timer.java:555) at   java.util.TimerThread.run (Timer.java:505)

And error occurs when you set the new String in the Label. The updateTicker() method is returning String as expected.

    
asked by anonymous 22.06.2017 / 20:22

1 answer

1

Do not mix awt with JavaFX.

Make a note with @FXML of everything in the .fxml file.

Use Timer and TimerTask for processes that do not change the controls in the UI, for example some action that must be performed in background while the program is running.

Use the javafx.animation.* package classes to try to change elements in the UI during the execution of the application, which is your case. There is, for example, the class Timeline that serves just to this purpose.

Timeline oneMinuteTimeline = new Timeline(new KeyFrame(Duration.minutes(1), event -> {
   helloWorld.setText(updateTicker());
}));

oneMinuteTimeline.setCycleCount(Timeline.INDEFINITE); // Executar indefinidamente.
oneMinuteTimeline.play();

This will change the value of the label helloworld every minute.

I've created a small gist example, updating a Label to each second . The result is this:

    
28.06.2017 / 18:37