Is it possible to restrict the files available to a specific directory with a JFileChooser?

124 views Asked by At

Is it possible to create a JFileChooser object that limits the choosable files to a specific directory? As in, I don't want the user to be able to navigate anywhere other than the directory that I set.

For context, I am making a simple game that is based loosely on the MVC model, and that has both a command line and graphical interface. Although the GUI is one class, I would like the possibility for the user to be able to use the command line interface for the controller and the GUI for the view, and vice versa. For the command line version, which I have already written, I have provided the user with the options of listSavedGames(), loadSavedGame(String fileName), and saveGame(String fileName) (all limited to the saved games in a specific directory, 'saved games'. The problem I am trying to solve is how I would do this for the GUI version, which I am using Swing to build. I envisage the user being able to click on something like 'Load/Save game', which lists the saved games (listSavedGames()) and an empty text box where the user can provide a string by clicking or typing, with buttons for 'Save', 'Load', and 'Cancel'.

I have looked into JFileChooser and while it would sort of help, it doesn't really provide the functionality for listing saved games, and I also can't work out how it would only show files in the 'saved games' directory. I have seen that you are able to set the JFileChooser object to only display directories or indeed any specific file type, but this isn't what I'm after.

If the answer is beyond JFileChooser and is to build a custom component, then any help on that would be appreciated too. Thanks in advance.

1

There are 1 answers

0
camickr On BEST ANSWER

You can create a custom FileSytemView that allows you to only specify a single file root.

Check out Single Root File Chooser for an example of this approach.