1

How to/what's the best way to handle a JFileChooser in an MVC architecture in Java? My controller is listening for events in the main GUI and it works for the buttons on it, i.e., the controller calls the appropriate methods on the Model and it (the Controller) updates the View. The problem is that now i want to add a JFileChooser and i want to update the Model, via the Controller, with the selected file's fullpath.
I'm using the code in this answer How to manage view updates from controllers in a Java Swing app developed by @Hovercraft Full Of Eels as a base for my project.
How can i do this?

Community
  • 1
  • 1
DaveQuinn
  • 189
  • 1
  • 6
  • 19

1 Answers1

4

Here's a bare bones version. This method came from one of my ActionListener classes that was triggered by a JMenuItem.

You would have to pass an instance of your GUI Frame and an instance of your GUI model to the class that contains this method.

protected int chooseOpenFile() {
    JFileChooser fileChooser = new JFileChooser(model.getSavedInputFile());

    int status = fileChooser.showOpenDialog(frame.getFrame());

    if (status == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        model.setSavedInputFile(selectedFile);
    }

    return status;
}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • Thank you @Gilbert Le Blanc. This didn't occur to me, me being a noob, becaude i didn't know whether passing references of the model to the view is in fact a good or a bad practise. Will try ths, but i'm pretty confident it will work. – DaveQuinn Mar 13 '13 at 14:50
  • 1
    @PMMP: You have to pass instances of the GUI Frame, which specifies the JFrame, and the GUI Model, to most of the GUI classes. Components reading from and writing to the GUI model is what keeps the GUI components from coupling. In a large system, your GUI model is separate from the application model. The GUI model is the application view in MVC. – Gilbert Le Blanc Mar 13 '13 at 14:54
  • sorry @Gilbert Le Blanc, i have just one more question. Where and how should i create the JFileChooser? Should i create it in the main class with the model the view and the controller, set it visible as a response to the action performed on the "Open File" button and then set it to invisible? Or should i create the view each time in the controller as response to the action performed on the "Open File" button? What do you think would be the best approach? – DaveQuinn Mar 13 '13 at 17:29
  • 2
    You should create the view each time in the ActionListener of the controller as response to the action performed on the "Open File" button. You're also going to need to expand on the JFileChooser. Read this excellent article for the details: http://java-articles.info/articles/?p=57 – Gilbert Le Blanc Mar 13 '13 at 17:32