user7405277
user7405277

Reputation:

Swap JavaFX scene when clicking a button

I am trying to create a program to teach people about GNU/Linux and the command line, I have my main.java

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
    Stage window;

    public static void main(String[] args) {
        launch(args); 
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        Parent root = FXMLLoader.load(getClass().getResource("login.fxml"));
        primaryStage.setTitle("Learnix");
        primaryStage.setScene(new Scene(root, 800, 500));
        primaryStage.show();
    }
}

And the controller to go with it.

package sample;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import java.io.IOException;

public class loginController {
    public Button loginBtn;
    public void loginBtnClick() throws IOException {
        System.out.println("You are logged in");
     }
}

I have tried things such as:

FXMLLoader.load(getClass().getResource("lessons.fxml"));

But I can't figure out how to get it to swap scenes. I have seen many tutorials on YouTube and it Stack Overflow but many of them have all of the JavaFX on the main.java and not in separate files as I am using scenebuilder.

Thank you.

Upvotes: 4

Views: 4442

Answers (1)

Sergey Grinev
Sergey Grinev

Reputation: 34478

You can either call Stage.setScene() to change the whole scene or just substitute a root to the new one by Scene.setRoot():

Parent newRoot = FXMLLoader.load(getClass().getResource("lessons.fxml"));
primaryStage.getScene().setRoot(newRoot);

Upvotes: 4

Related Questions