Store dynamic screen with multiple stages

后端 未结 2 1755
终归单人心
终归单人心 2020-12-22 06:00

I´ve got 2 different screens, in the first screen the user can load images and the other one is just a single button (the stage is invisible so the stage has to be different

2条回答
  •  攒了一身酷
    2020-12-22 06:34

    You have to store a reference to your stage content, so you don't have to reinstantiate it. One possibility is to store it in the mainController and provide an EventHandler to your subController, to switch the stage

    public interface ScreenController {
            void setOnSwitchStage(EventHandler handler);
    }
    
    public class Screen1Controller implements Initializable, ScreenController {
    
        @FXML
        private Button btnSwitchScreen
    
        public Screen1Controller() {
        }
    
        @Override
        public void initialize(URL location, ResourceBundle resources) {
        }
    
         @Override
        public void setOnSwitchStage(EventHandler handler) {
            btnSwitchScreen.setOnAction(handler);
        }
    }
    
    public class YourApp extends Application {
    
        @Override
        public void start(Stage primaryStage) throws Exception {
            Stage secondaryStage = new Stage();
    
            initScreen(primaryStage, secondaryStage, "screen1.fxml");
            initScreen(secondaryStage, primaryStage, "screen2.fxml");
    
            primaryStage.show();
        }
    
        private void initScreen(Stage parentStage, Stage nextStage, String resource) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource(resource));
        Scene scene = new Scene(loader.load());
        parentStage.setScene(scene);
    
        ScreenController screenController = loader.getController();
        screenController.setOnSwitchStage(evt -> {
            nextStage.show();
            parentStage.hide();
        });
    }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

提交回复
热议问题