简体   繁体   English

是否可以使用JFileChooser限制可用于特定目录的文件?

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

Is it possible to create a JFileChooser object that limits the choosable files to a specific directory? 是否可以创建一个JFileChooser对象,将可选择的文件限制到特定目录? 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. 就上下文而言,我正在制作一个简单的游戏,该游戏大致基于MVC模型,并且具有命令行和图形界面。 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. 尽管GUI是一类,但我希望用户能够使用命令行界面作为控制器,使用GUI作为视图,反之亦然。 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'. 对于我已经编写的命令行版本,我为用户提供了listSavedGames()loadSavedGame(String fileName)saveGame(String fileName) (全部限于特定目录中保存的游戏,“我要解决的问题是我将如何使用Swing构建GUI版本的图形,我希望用户能够单击“加载/保存游戏”之类的内容,保存的游戏( listSavedGames() )和一个空文本框,用户可以通过单击或键入带有“保存”,“加载”和“取消”按钮的字符串来提供字符串。

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. 我研究了JFileChooser,虽然它会提供一些帮助,但它实际上并未提供列出已保存的游戏的功能,而且我也无法弄清楚它仅显示“已保存的游戏”目录中的文件的方式。 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. 我已经看到您可以将JFileChooser对象设置为仅显示目录或实际上任何特定的文件类型,但这不是我要的。

If the answer is beyond JFileChooser and is to build a custom component, then any help on that would be appreciated too. 如果答案超出了JFileChooser的范围,而是要构建自定义组件,那么对此的任何帮助也将不胜感激。 Thanks in advance. 提前致谢。

You can create a custom FileSytemView that allows you to only specify a single file root. 您可以创建一个自定义FileSytemView ,它仅允许您指定一个文件根。

Check out Single Root File Chooser for an example of this approach. 请查看“ 单根文件选择器”以获取此方法的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM