How to update a Label automatically every minute?

Asked

Viewed 685 times

1

I am wanting to make an application that checks the price of a product every minute.

In my Code test this as follows:

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 don’t know how to fix it:

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 to the Label. The method updateTicker() is returning String as expected.

  • The public Label helloWorld is being instantiated and you are assigning a reference to the instance of MyTask when the instance? This seems to be the variable that is null.

  • She’s instantiated as soon as I carry mine FXML. When the Access in which you want another class I do not have this error. Only when I put it within the Method run()

  • Can the timer be instantiated before the FXML load? Try to put in run() if (helloWorld != null) helloWorld.setText(updateTicker());

  • It really was null, I changed the moment I call my Method criarTask() and it worked. Thank you

1 answer

1


Do not mix awt with Javafx.

Note with @FXML everything that is file element .fxml.

Utilize 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 package classes javafx.animation.* to try to change elements in the UI while running the application, which is your case. There is, for example, the class Timeline which serves precisely 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 label value helloworld every minute.

I created a little gist example by updating a Label every second. The result is this:

update label

Browser other questions tagged

You are not signed in. Login or sign up in order to post.