napstyr maceda
napstyr maceda

Reputation: 179

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

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
        }
    }    

}

Upvotes: 0

Views: 1097

Answers (2)

napstyr maceda
napstyr maceda

Reputation: 179

I got a better solution! Instead of doing the timer based task in another class that cause to run in another thread, I include it in its own class method so It can get the same thread. Here is my code.

**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();

Upvotes: 0

tomsontom
tomsontom

Reputation: 5887

Sure pass the stage and call stage.hide() - because you are not in the FX-Thread you need to wrap the call into Platform.runLater()

Upvotes: 1

Related Questions