webstudent webstudent - 4 months ago 31
Java Question

JavaFX - Open a scene from another class event

I've got a "Main.java" which holds all of my JavaFX, multiple scenes of an entire program are stored here and it's become very difficult to read. I'd like to try to store each "screen"(scene) in a separate .java class so that I may more easily find and make changes etc. I'm new to JavaFX and still learning OOP.

In the sample below I would like to open a new scene (from a separate .java class) on a button click event. I have this currently working in the single class. But don't know how to approach this in another file. I also need to pass two array lists into the separate class to populate tables.

Below is a sample of my tinkering.

All help is appreciated, Thanks.

The button:

goToNextScene = new Button("View next scene");
goToNextScene.setOnAction(e -> window.setScene(AnotherClassA.sceneLayout, aList, bList));
// another try:
goToNextScene.setOnAction(e -> AnotherClassA.sceneLayout(aList, bList));

The new class: (Just a screen with more buttons and soon two tables to display the passed array lists)

public class AnotherClassA {

private BorderPane bP;
private HBox hBtnMenu;
private Button hMenuBtnA, hMenuBtnB, returnBtn;
public Scene sceneLayout;

public Scene sceneLayout(ArrayList aList, ArrayList bList) {

// array lists not used yet, but will come

hBtnMenu = new HBox();
hBtnMenu.setPadding(new Insets(10,10,10,10));

hMenuBtnA = new Button("Btn A");
//hMenuBtnA.setOnAction(e -> window.setScene(AnotherClassA.sceneA));

hMenuBtnB = new Button("Btn B");
//hMenuBtnB.setOnAction(e -> window.setScene(AnotherClassB.sceneB));

returnBtn = new Button("Return to Home");
//returnBtn.setOnAction(e -> window.setScene(Main.splashScene));

hBtnMenu.getChildren().addAll(hMenuBtnA, hMenuBtnB, returnBtn);

bP = new BorderPane();

animalSceneLayout = new Scene(bP, 1200, 760);

return asceneLayout;


Thanks in advance


You can extend Scene with all of your classes, doing something like public class SceneA extends Scene and create a constructor like

public SceneA(Parent root, ArrayList a, ArrayList b) { super(root); } 


goToNextScene.setOnAction(e -> window.setScene(new SceneA(new AnchorPane(), aList, bList));