我正在尝试从任务(线程)关闭JavaFX中的阶段。
为了完成这一点,我尝试将对Stage的引用传递给扩展Task的类,在那里设置当前Stage。
然后在call()结束时关闭Stage。但是.close()和。hide()并没有隐藏/关闭Stage。
类:SampleStage
public class SampleStage extends Application {
@Override
public void start(final Stage primaryStage) throws Exception {
primaryStage.setTitle("JavaFx Dialog");
final Button btn = new Button();
btn.setText("Click me to display popup dialog");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
Stage dialog = new Stage();
Taskee task = new Taskee();
dialog.initStyle(StageStyle.UTILITY);
task.setStage(dialog);
new Thread(task).start();
Scene scene2 = new Scene(new Group(new Text(25, 25, "Hello World!")));
dialog.setScene(scene2);
dialog.show();
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
类Taskee:
进口javafx.concurrent.Task;进口javafx.stage.Stage;
public class Taskee extends Task<Void>{
private Stage stage;
@Override
protected Void call() throws Exception {
for(int i=0;i<10;i++){
//@DoSomething()
for(long l=0;l<10000;l++);
System.out.println("i=" + i);
}
getStage().close();
getStage().hide();
return null;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
}
注意:getStage().getScene().getWindow().hide();
也不工作
hide()
方法必须在FX Application线程上调用。(在Java 8中,你的代码实际上会抛出一个异常。)
使用Task
的setOnSucceeded()
处理程序在以下情况下关闭阶段:
public class Taskee extends Task<Void>{
private Stage stage;
public Taskee() {
setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
if (stage != null) {
stage.hide();
}
}
});
}
@Override
protected Void call() throws Exception {
for(int i=0;i<10;i++){
//@DoSomething()
for(long l=0;l<10000;l++);
System.out.println("i=" + i);
}
return null;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
}