Using a single Stage
(window) and switching between 2 Scene
s or using 2 windows switching between them is completely up to you. Here is an example code on how to do it using 1 Stage
and switching between Scenes
. I need to give the credit for this code to @thenewboston who has a very nice, useful and easy to follow JavaFX tutorial on YouTube:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
public class Main extends Application {
Stage window;
Scene scene1, scene2;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
window = primartStage;
Label label1 = new Label("Welcome to the first scene!");
Button button1 = new Button("Go to scene 2");
button1.setAction(e -> window.setScene(scene2));
// Layout 1 - children are laid out in vertical column
VBox layout1 = new VBox(20);
layout1.getChildren().addAll(label1, button1);
scene1 = new Scene(layout1, 200, 200);
// Button 2
Button button2 = new Button("Go back to scene 1");
button2.setAction(e -> window.setScene(scene1));
// Layout 2
StackPane layout2 = new StackPane();
layout2.getChildren().add(button2);
scene2 = new Scene(layout2, 600, 600);
window.setScene(scene1);
window.setTitle("Switching Scenes");
window.show();
}
}