简体   繁体   中英

JavaFX - Open a Scene from another class event

I've got a Main.java which holds all of my JavaFX code, 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.

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.setSpacing(10);
        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();
       bP.setTop(hBtnMenu);

       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); } 

Then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM