0

I am working on an JavaFX app and I have decided to separate my fxml files / controllers to spread things out a bit. I have 4 main fxml files / controllers which are then included into the main fxml file and placed into a border pane (the 4 sections are numbered and outlined in red in the image link below). However, I would like to reference the controllers within the other controllers. So far, I have been using the static keyword. however, I am not really happy with that solution and was wondering if there is a cleaner way to do this. This is a snippet of how I have accomplished this so far:

Located Within File Browser Controller

@FXML
private void handleImportButtonAction(ActionEvent event) {

    importCount = 0;

    // Pushes the import songs task to run on the background instead of the UI Thread
    Runnable importTask = new Runnable() {

        @Override
        public void run() {

            List<Song> importSongsList = new ArrayList<>();

            importSongsList = importFilesForImportButton(fileBrowser.getSelectionModel().getSelectedItems(), importSongsList);

            SongDisplayWindowController.getWindowDisplaySongs().addAll(importSongsList);

            //TODO: Log this to the console window and display an files that couldn't be imported           
            System.out.println("You succesfully imported " + importCount + " files!");

        }   
    };      
    new Thread(importTask).start();
}

Located Within Song Display Window Controller

public class SongDisplayWindowController implements Initializable{

    private static ObservableList<Song> windowDisplaySongs;

    public static ObservableList<Song> getWindowDisplaySongs() {
        return windowDisplaySongs;
    }
}

Is it possible for me to use something like Spring based DI to basically make the controllers singletons and then just inject the controllers into the other controllers where I need access to their stuff?

Application Screenshot with Controllers labeled

oznomal
  • 439
  • 2
  • 8
  • 22
  • 1
    You can't make the controllers singletons: that makes no sense (think about what would happen if you loaded the same FXML file twice...). The standard approach in UI design is called "Model-View-Controller" (there are several variants); basically this will mean you don't need access to one controller in another controller. Each controller has access to a shared model, observes it, and changes data in it. You can use Spring (or another DI framework) to inject the model into the controllers. See https://stackoverflow.com/q/40539310 and https://stackoverflow.com/q/32342864 – James_D Apr 07 '18 at 22:29
  • Basically, your `windowDisplaySongs` belongs in the model, not the controller. – James_D Apr 07 '18 at 22:36

0 Answers0