Two rules for multithreading in JavaFX:
- Code that modifies the user interface (creates a
Stage or changes the properties of nodes that are part of the scene graphics) must be run on the JavaFX Application Theme. Violation of this rule will either throw an IllegalStateException or lead to unpredictable behavior. - Code that takes a long time to execute must be executed in the background thread (i.e. not in the FX application thread). Violation of this rule will cause the user interface to become unresponsive.
Your code violates the first rule because it calls the ProgressForm constructor in the background thread. You must first set up the user interface, show the dialog, and then start the background thread.
Note that there is no need to relink the progress properties of the progress bar and indicator to the progress property of the task. Once he is bound, he will remain bound until you untie him.
It is very difficult to fix your code, since your background task does not actually do anything that is required at any time. Here's a version of what you are doing, just a pause:
import javafx.application.Application; import javafx.concurrent.Task; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.control.ProgressIndicator; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; public class ProgressDialogExample extends Application { @Override public void start(Stage primaryStage) { Button startButton = new Button("Start"); startButton.setOnAction(e -> { ProgressForm pForm = new ProgressForm();
source share