-2

I am trying to build a clock in javafx but the GUI crashes when I try using an infinite loop.

    while (true) {
            Date time = new Date();
            
             // mins and hour are labels
            
            if (time.getMinutes() < 10) {
                mins.setText("0" + Integer.toString(time.getMinutes()));    
            } else {
                mins.setText(Integer.toString(time.getMinutes()));
            }
            
            if (time.getHours() < 10) {
                hour.setText(0 + Integer.toString(time.getHours()));    
            } else {
                hour.setText(Integer.toString(time.getHours()));
            }
            
        }

I heard I can use something called a thread but I didn't really understand how to properly implement it.

OriFl
  • 117
  • 4
  • 7

2 Answers2

1

Looks like you are using an infinite loop in the UI thread. You should keep track of time in a background thread, but update the UI in UI thread.

To run in background thread, use:

new Thread(new Runnable(){
    public void run(){
        //your code here.
    }
}).start();

To run in UI thread, use:

Platform.runLater(new Runnable(){
    public void run(){
        //your code here.
    }
});
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
0

That is perfectly reasonable. Never block the main thread! Use an additional thread in order to achieve your goal.

Task<Void> workingTask = new Task<Void>() {
    @Override
    public Void call() {

    while (true) {
        //yourcode
    }

}

and use Platform.runLater(()-> { //yourcode}); in order to send small tasks to main javafx thread. For e.g.

Platform.runLater(() -> {
    mins.setText(Integer.toString(time.getMinutes()));
});
user2805346
  • 302
  • 2
  • 11