JFileChooser 在 OS X 中返回不正确的路径(仅限文件夹模式)
我在 java swing 中遇到问题,用户必须选择一个文件夹,所以我使用下面的代码。
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(fc.showDialog(singleton, SELECT) == JFileChooser.APPROVE_OPTION) {
File folder = fc.getSelectedFile();
String path = folder.getPath() + File.separatorChar + MYAPPFOLDER;
}
现在,用户可以通过两种方式选择文件夹
- 导航到文件夹,然后选择文件夹
- 导航到文件夹,进入文件夹,然后单击选择
这两种方法在 Windows 上都可以正常工作,但在 OS X 上,我得到
If I do 1 : path = Users/
如果我执行 2 : path = Users/
如何避免这种情况第二个案例?
提前致谢。
I have a problem in java swing where the user has to select a folder, so I am using the code below.
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(fc.showDialog(singleton, SELECT) == JFileChooser.APPROVE_OPTION) {
File folder = fc.getSelectedFile();
String path = folder.getPath() + File.separatorChar + MYAPPFOLDER;
}
Now there are 2 ways a user may select the folder
- Navigate to the folder and select the folder
- Navigate to the folder, go into the folder, and click select
Both ways work fine on windows but on OS X, I get
If I do 1 : path = Users/<username>/Desktop/MYAPPFOLDER
If I do 2 : path = Users/<username>/Desktop/Desktop/MYAPPFOLDER
How do I avoid this 2nd case?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是 showDialog 不知道这是加载还是保存操作,因此它为您提供了用于放置新文件/文件夹名称的文本框。当您单击要进入的文件夹时,该文本框被设置为“桌面”它(作为双击的第一次单击),如果用户然后按 SELECT,该对话框假定您要使用该名称创建一个新文件夹并将其返回到路径中。
一种解决方案是改用 showOpenDialog 调用,并手动更改选择器的标题并将按钮批准为 SELECT。这样,用户就永远不会看到新目录文本框。
代码看起来像这样:
The problem is that showDialog doesn't know whether this is a load or save operation, so it gives you the textbox to put the new file/folder name in. This is set to 'Desktop' when you click on the folder to go into it (as the first click of a double-click) and if the user then presses SELECT, the dialog assumes you want to create a new folder with that name and returns it in the path.
One solution is to use the showOpenDialog call instead, and manually change the chooser's title and approve buttons to SELECT. That way, the user never sees the new directory textbox.
The code would look something like this: