0

I created a scene in class1, then i created a scene2 in class2. How to switch between them?

public class class1 extends Application{

Stage window1;
BorderPane layout1;
Scene scene1;

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

@Override
public void start(Stage primaryStage) throws Exception {
    window1 = primaryStage;
    window.setTitle("Stage 1");

    // And here is a button which switchs between scenes or stages,
    //i dont know what is better.So:

button.setOnAction(e -> ?????????)



    scene1 = new Scene(layout1, 800,600);
    window1.show();
}
}

And here is the second class in which i have another scene.

public class class2 extends Application{

Stage window2;
BorderPane layout2;
Scene scene2;

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

@Override
public void start(Stage primaryStage) throws Exception {
    window2 = primaryStage;
    window2.setTitle("Stage 2");

    scene2 = new Scene(layout, 800,600);
    window2.show();
}
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
szufi
  • 219
  • 1
  • 2
  • 9
  • 4
    The approach you have chosen will not work as there can only be one `Application` per runtime. For the rest take a look at http://stackoverflow.com/questions/37200845/how-to-switch-scenes-in-javafx – hotzst May 13 '16 at 13:26

2 Answers2

0

I wrote this controller to keep track of the different scenegraphes and switch the content of my Stage with no hassle.

Maybe you want to take a look at FXML: http://docs.oracle.com/javafx/2/fxml_get_started/why_use_fxml.htm#CHDCHIBE

public class ScreenController {
    private HashMap<String, Pane> screenMap = new HashMap<>();
    private Scene main;

    public ScreenController(Scene main) {
        this.main = main;
    }

    protected void addScreen(String name, Pane pane){
         screenMap.put(name, pane);
    }

    protected void removeScreen(String name){
        screenMap.remove(name);
    }

    protected void activate(String name){
        main.setRoot( screenMap.get(name) );
    }
}

So I can write:

ScreenController screenController = new ScreenController(scene);
screenController.add("layout1", layout1 );
screenController.add("layout2", layout2 );
screenController.add("testSwitch", FXMLLoader.load(getClass().getResource( "TestSwitch.fxml" )));

button.setOnAction(e -> screenController.activate("layout2"));

This was a workaround for a fullscreen application, where the MacOS fullscreen transition was shown every time a stage switches its scene.

MrEbbinghaus
  • 963
  • 7
  • 15
0

put this in your Controller. You can use anything (like button,label etc.) to get access to your Stage (best inside an eventhandler from Button).

Stage stage = (Stage) AnyThingOnScene.getScene().getWindow();
Parent root = FXMLLoader.load(getClass().getResource("someFile.fxml"));
Scene scene = new Scene(root,420,360);
stage.setScene(scene);
K4V4N
  • 1