喜欢主题:当我尝试将子项添加到Pane时,为什么Task会停止?如何在不离开任务的情况下解决这个问题?下面的工作示例:
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Ellipse;
import javafx.stage.Stage;
public class TEST extends Application {
private Pane displayPane;
public Parent createContent() {
/* layout */
BorderPane layout = new BorderPane();
/* layout -> center */
displayPane = new Pane();
displayPane.setMinSize(200, 200);
displayPane.setMaxSize(200, 200);
/* return layout */
layout.setCenter(displayPane);
return layout;
}
@Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
stage.show();
startTask();
}
public void startTask() {
Task task = new Task<Void>() {
@Override
public Void call() {
// This works fine.
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
for (int i = 0; i < 5; i++) {
System.out.println("Iteration no.: " + i);
Ellipse ellipse = new Ellipse(100, 100, 10, 10);
ellipse.setFill(Color.BLACK);
// Here task stops on iteration np.: 0.
displayPane.getChildren().add(ellipse);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
displayPane.getChildren().remove(displayPane.getChildren().size() - 1);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
return null;
}
};
new Thread(task).start();
}
}