public class SwitchScene extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
public class FXMLDocumentController {
@FXML
private Label label;
@FXML
private void handleButtonAction(ActionEvent event) {
try {
Parent root = FXMLLoader.load(getClass().getResource("SecondScreen.fxml"));
Scene dashboard=new Scene(root);
//This line gets the Stage Information
Stage window=(Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(dashboard);
window.show();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class SecondScreenController {
public void MoveBack(ActionEvent event){
try {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene dashboard = new Scene(root);
//This line gets the Stage Information
//here we get the stage from event action and setting the root element in the scene and display scene with stage object (window) which is retrieved from action event
Stage window=(Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(dashboard);
window.show();
} catch (IOException ex) {
Logger.getLogger(SecondScreenController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//FXMLDocument.xml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" fx:controller="switchscene.FXMLDocumentController">
<children>
<Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleButtonAction" fx:id="button" />
<Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
</children>
</AnchorPane>
////SecondScreen fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="switchscene.SecondScreenController">
<children>
<Button fx:id="btnMove" layoutX="269.0" layoutY="188.0" mnemonicParsing="false" onAction="#MoveBack" text="Move Back" />
</children>
</AnchorPane>