Issue
I'm working on a Text Editor in javaFX and I want a little StartUp Window before the Text Editor opens. I want that the StartUp Window is closing after Time and then the Text Editor window opens. The problem is, the StartUp Window isn't showing when I start the program. And when the time is over, the TextEditor window is showing shortly but then the program is crashing and shows me the Syntax-Error:
InvocationTargetException
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
MainWindow.openAnother(primaryStage);
primaryStage.setScene(new Scene(root, 300, 200));
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
MainWindow Class:
package sample;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MainWindow {
public static void openAnother(Stage primaryStage) {
try {
Thread.sleep(4345);
primaryStage.close();
Fenster(primaryStage);
} catch(InterruptedException e) { }
}
public static void Fenster(Stage nextStage) {
StackPane root = new StackPane();
//TODO TextEditor-Code
Scene scene = new Scene(root);
nextStage.setScene(scene);
nextStage.setFullScreen(true);
nextStage.show();
}
}
Solution
Use Timelines.
This example launches a splash screen stage (primaryStage), then three seconds later the textEditorStage shows and then after one second the splash screen stage will close.
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Example extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(new AnchorPane(), 200, 200));
primaryStage.setTitle("Splash Screen");
primaryStage.setAlwaysOnTop(true);
primaryStage.show();
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(3000), event -> {
Stage textEditorStage = new Stage();
textEditorStage.setScene(new Scene(new AnchorPane(), 400, 400));
textEditorStage.setTitle("Text Editor");
textEditorStage.show();
Timeline timeline2 = new Timeline(new KeyFrame(Duration.millis(1000), event2 -> {
primaryStage.close();
}));
timeline2.play();
}));
timeline.play();
}
}
Answered By - smbo_