150k views
2 votes
how do i make it so that when a button is click in javafx controller, a new scene is created and displayed

User Nick Masao
by
8.5k points

1 Answer

5 votes

Final answer:

In JavaFX, you can create a new scene and display it when a button is clicked in the controller class.

Step-by-step explanation:

In JavaFX, you can create a new scene and display it when a button is clicked in the controller class. This can be done by implementing an event handler for the button's action event. Inside the event handler, you can create a new scene using the Scene class and set it as the current scene using the setScene method of the Stage class.

Here's an example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {
public static void main(String[] args) {
launch(args);
}

public void start(Stage primaryStage) {
Button button = new Button("Click Me");
button.setOnAction(e - > {
Scene newScene = new Scene(new StackPane(), 400, 300);
primaryStage.setScene(newScene);
primaryStage.show();
});

StackPane root = new StackPane();
root.getChildren().add(button);
Scene scene = new Scene(root, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
}

In this example, a new scene is created with a StackPane as its root. When the button is clicked, the new scene is set as the current scene and displayed.

User Amokrane Chentir
by
7.9k points