Java 如何将 JFileChooser 开始目录更改为桌面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22486230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change JFileChooser start directory to desktop?
提问by lnk
I want to change JFileChooser
start directory to desktop. So, in my computer I wrote:
我想将JFileChooser
开始目录更改为桌面。所以,在我的电脑上,我写道:
JFileChooser fc = new JFileChooser("C:\Users\LNK\Desktop");
The problem is, when I compile my code and run program in another computer it doesn't work because there are no C:\\Users\\LNK\\Desktop
path. So, is there some kind of "apsolute" path of desktop?
问题是,当我编译我的代码并在另一台计算机上运行程序时,它不起作用,因为没有C:\\Users\\LNK\\Desktop
路径。那么,是否有某种“绝对”的桌面路径?
回答by RKC
use this ,
用这个 ,
String desktopPath = WindowsUtils.getCurrentUserDesktopPath();
回答by Eugene Ryzhikov
You can use a user.home
system property to get user directory.
So your code would look like
您可以使用user.home
系统属性来获取用户目录。所以你的代码看起来像
String userDir = System.getProperty("user.home");
JFileChooser fc = new JFileChooser(userDir +"/Desktop");
回答by Rodney Palmer
Here is another option for getting to the Windows desktop:
这是进入 Windows 桌面的另一种选择:
fileChooser.setCurrentDirectory(new File("C:\"));
Action details = fileChooser.getActionMap().get("Go Up");
details.actionPerformed(null);
details.actionPerformed(null);
If you leave off the last line, you will get to "Computer"
如果你离开最后一行,你将进入“计算机”