2

I have two seperate Controllers and FXML-files. In the first controller you control the main window, here you can press a button and open a new Window.

I want to prevent the user from opening as many windows as he wants. He should only be able to open one window and close it again before he can open the next one.

This is the code that gets executed when you press the button, that I'm talking about. It opens my window perfectly, but I can still open more windows in the background which is not what I want.

I hope you can provide me some help. Thanks in advance

   @FXML
   private void addSongsToSelectedPlaylist() throws IOException {


    if (tempPlaylistName!="Library"){

        // WILL LOAD THE STAGE OF THE POPUP WINDOW AND PROVIDE THE CONSTRUCTOR THE PLAYLIST NAME
      //  AddSongController addSongController = new AddSongController();

     //   addSongController.enterSelectionMode(tempPlaylistName);


        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("addSongToPlaylistPopUp.fxml"));
            Parent root1 = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.initModality(Modality.WINDOW_MODAL);
            stage.getIcons().add(new Image("sample/images/Music-icon.png"));
            stage.setResizable(false);
            stage.setAlwaysOnTop(true);

            stage.setTitle("Add songs to your playlist");
            stage.setScene(new Scene(root1));
            stage.showAndWait();

        } catch (IOException e){

            System.out.println(e.getCause());

        }
  • 2
    You'll need a reference to some shared state (could be the `Window` itself) that checks if the other window `isShowing`. If it is, don't show the new one. You could even disable the button so long as the `showing` property is `true` (e.g. with a binding). – Slaw Jan 16 '19 at 21:18
  • 2
    Also, regarding `if (tempPlaylistName != "Library")`, see [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/). – Slaw Jan 16 '19 at 21:29
  • 1
    This question is similar: https://stackoverflow.com/questions/52693199/check-if-a-stage-is-already-open-before-open-it-again-javafx – Slaw Jan 16 '19 at 22:30
  • You could also close the first window in the initializer of the newly opened window. All you need is a reference of the left-open window. In order to go easy on the user you might want to establish some sort of exitAndClose() method that asks and saves in case there was something usefule in that window. – benji2505 Jan 17 '19 at 00:15
  • 1
    Possible duplicate of [JavaFX Stage Modality](https://stackoverflow.com/questions/31046945/javafx-stage-modality) – Damien Jan 17 '19 at 10:53

1 Answers1

2

You can set the modality to APPLICATION_MODAL to prevent the application from opening any new window until the first one is closed:

   stage.initModality(Modality.APPLICATION_MODAL);
Damien
  • 1,161
  • 2
  • 19
  • 31