Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change JFileChooser start directory to desktop?

Tags:

java

swing

I want to change JFileChooser start directory to desktop. So, in my computer I wrote:

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?

like image 855
lnk Avatar asked Mar 18 '14 17:03

lnk


People also ask

Which of the following is built in dialog that lets a user select a file JFileChooser?

The object of JFileChooser class represents a dialog window from which the user can select file.

How do I save a JFrame in Java?

If you want to save and reconstruct a JFrame, you'll need to save the data being used (in the labels and boxes) and write code to parse and reconstruct from the saved data. This is why you should build the logic model for your application before adding a GUI to it.


2 Answers

You can use a user.home system property to get user directory. So your code would look like

String userDir = System.getProperty("user.home");
JFileChooser fc = new JFileChooser(userDir +"/Desktop");
like image 92
Eugene Ryzhikov Avatar answered Oct 04 '22 09:10

Eugene Ryzhikov


Here is another option for getting to the Windows desktop:

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"

like image 31
Rodney Palmer Avatar answered Oct 04 '22 08:10

Rodney Palmer