I usually use a class Singleton to work with Stage
. So to switch between screens in controllers I call the loadNewStage
method of my class responsible for working Stage
.
HaveStage Class
public class HaveStage {
private static HaveStage haveStage = null;
private Stage stage;
private HaveStage(Stage stage) {
this.stage = stage;
}
public static HaveStage instance(Stage stage) {
if (haveStage == null) {
haveStage = new HaveStage(stage);
}
return haveStage;
}
public Stage getStage() {
return this.stage;
}
public void loadNewStage(Parent fxmlLoad) {
if (stage != null) {
Parent root = fxmlLoad;
Scene scene = new Scene(root);
stage.setScene(scene);
//stage.show();
}
}
}
Application Class
public class MinhaClasse extends Application {
private HaveStage haveStage;
@Override
public void start(Stage stage) {
this.haveStage = HaveStage.instance(stage);
Parent root = null;
Scene scene;
try {
root = FXMLLoader.load(getClass().getResource("/br/com/projeto/primeiraTela.fxml"));
} catch (IOException ex) {
Logger.getLogger(MinhaClasse.class.getName()).log(Level.SEVERE, null, ex);
}
scene = new Scene(root);
haveStage.getStage().setScene(scene);
haveStage.getStage().show();
}
}
Whenever you want to switch the screen call the loadNewStage
method on the controllers.
Example Driver
public class LoginScreenController {
@FXML
void login(InputEvent event) {
try {
Parent temp = FXMLLoader.load(getClass().getResource("/br/com/projeto/segundaTela.fxml"));
changeScreen(temp);
} catch (IOException ex) {
ex.getCause().printStackTrace();
new Notifications().errorNotification("Erro ao carregar nova tela!");
}
}
private void changeScreen(Parent fxmlLoad) {
HaveStage.instance(null).loadNewStage(fxmlLoad);
}
}