I usually use a class Singleton to work the Stage
. So to switch between screens in the controllers call the method loadNewStage
of my class responsible for working the 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 method loadNewStage
in the controllers.
Controller Example
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);
}
}
Hi @Ronaldo Alves. It is beneficial for the community to give a feedback if the problem has been solved or if it still remains. I left an answer but you did not give a return.
– Paulo Weverton