0

Is it possible to close stage from other class method in javafx 2?

I am developing little application but get stacked with this problem. I just want to close a loaded Login FXML GUI from other class method(TimerScheduler) after a period of time. I know that it is weird to close a login stage after a second but I have also some use of it if that is possible. Thank you in advance!

Here a sample of my code:

**Main.java**

@Override
public void start(Stage primaryStage) throws IOException {

    // Load the stage from FXML
    AnchorPane page = (AnchorPane) FXMLLoader.load(getClass().getResource("/fxml/FXMLLogin.fxml"));
    Scene scene = new Scene(page);
    primaryStage.setScene(scene);
    primaryStage.setResizable(false);
    primaryStage.setTitle("Admin Login");
    primaryStage.show();

    // Run the timer to execute task
    Timer timer = new Timer();
    TimerScheduler doTask = new TimerScheduler(timer);
    int firstSart = 1000;
    int period = 1000;
    timer.schedule(doTask,firstSart,period);
}


**TimerScheduler.java**

public class TimerScheduler extends TimerTask{

    Timer timer;
    int count = 0;

    public TimerScheduler(){}

    public TimerScheduler(Timer timer){
        this.timer=timer;
    }

    @Override
    public void run() {
        count++;

        if(count==30){ // execute after 30 seconds
            // I want to close the stage here
        }
    }    

}
4

2 回答 2

1

确定通过阶段并调用 stage.hide() - 因为您不在 FX-Thread 中,您需要将调用包装到 Platform.runLater()

于 2013-07-25T11:40:19.563 回答
0

我有一个更好的解决方案!我没有在另一个类中执行导致在另一个线程中运行的基于计时器的任务,而是将它包含在它自己的类方法中,以便它可以获得相同的线程。这是我的代码。

**Main.java**

Timeline TimerTaskExec = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {

@Override
public void handle(ActionEvent event) {

    count++;

    if(count==30){
        // do the task
        stage.close();
    }

}

}));

TimerTaskExec.setCycleCount(Timeline.INDEFINITE);
TimerTaskExec.play();
于 2013-07-26T06:16:13.643 回答