package taskcancel; import javafx.application.Application; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class TaskCancel extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage stage) { Group root = new Group(); final Button runButton = new Button("Run"); final Button cancelButton = new Button("Cancel"); final ProgressBar progressBar = new ProgressBar(); progressBar.setVisible(false); final Label resultLabel = new Label(); HBox hb1 = new HBox(5); hb1.getChildren().addAll(runButton, cancelButton, progressBar, resultLabel); runButton.setOnAction(new EventHandler() { public void handle(ActionEvent t) { progressBar.setVisible(true); final Task task = new Task() { @Override protected String call() throws Exception { final int MAX = 100000; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { int temp = i * j; } updateProgress(i, MAX); } return "Hello"; } }; runButton.disableProperty().bind(task.runningProperty()); progressBar.progressProperty().bind(task.progressProperty()); resultLabel.textProperty().bind(task.valueProperty()); cancelButton.setOnAction(new EventHandler() { public void handle(ActionEvent t) { task.cancel(true); } }); new Thread(task).start(); } }); root.getChildren().add(hb1); Scene scene = new Scene(root, 300, 250); stage.setScene(scene); stage.show(); } }