1

I'm new to JavaFX and have some trouble with threads. My application has to do something like this (hard pseudocode):

start(){
  startLoop(); //new thread
  displayThingsSavedToSharedVariable();
}



loop(){
  while (true){
    doThings();
    saveThingsToSharedVariable();
  }
}

I want to display output from loop() in JavaFX GUI up to date, one per line in the terminal, but I don't know how to synchronize a thread with loop() with JavaFX thread. The shared variable is only an - not working - example of what I want to achieve, the main question is how to dynamically print text to JavaFX GUI from an infinite loop in another thread.

nyi
  • 3,123
  • 4
  • 22
  • 45
1337_
  • 23
  • 4

1 Answers1

2

The correct way to update the javafx gui is to use Platform.runLater.

String mytext = deriveText();
Platform.runLater(()->{
    label.setText(mytext);
});

You could also consider using the Observable interface.

matt
  • 10,892
  • 3
  • 22
  • 34
  • you are Right @matt – Ng Sharma May 23 '18 at 08:53
  • I tried runLater(), but its code is executed only after I restart the GUI, for example 1. 1st run the program, infinite loop starts 2. runLater is never executed 3. I close the GUI, infinite loop keeps goins 4. I start the GUI and runLater() is finnally executed public void startServer(int capacity) { new Thread(() -> { Server server = new Server(capacity); server.start(); //here begins infinite loop Platform.runLater(() -> System.out.println("xD")); }).start(); } do I have to refresh GUI somehow? – 1337_ May 23 '18 at 08:59
  • @1337_ Can you include this more complete example in your original question? You need a javafx gui started to use Platform.runLater. It posts the runnable to an eventloop, and is eventually run on the application thread. Meanwhile your original thread is free to continue running. – matt May 23 '18 at 09:23
  • Observable interface was tht thing i was looking for, thanks. – 1337_ May 23 '18 at 09:49
  • ok, here comes another question. How can i chceck if ObservableList value changed in another thread and, depending on it infinitly display new value in GUI? (its going to be something like terminal log) – 1337_ May 23 '18 at 10:44
  • @1337_ you can add a listener. For example, you can have an ObservableValue and then add an changeListener. Note that the change listener will be called from the Platform thread. If you want a different thread to react. I would have your ChangeListener post a runnable to the thread you want it to run on. – matt May 23 '18 at 11:59