Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Starting a JFileChooser in the program directory  RSS feed

 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want the JFileChooser to open wherever the jar file for the program is located. I feel like I remember this being really easy on a PC, but I can't get it to work on Mac. The irritating thing is that I can get it so that the selected file is right where I want it, but the thing itself opens elsewhere.

The Code:



It prints a file in the correct directory, but just starts the filechooser in the default, I guess because the selected file doesn't exist. I guess I could make a dummy file in there, but that seems silly. I've also tried
setCurrentDirectory( file.getParentFile() ), but that doesn't seem to do anything different.

Thanks,
Nick
 
Norm Radder
Ranch Foreman
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you can get the location of the jar file by using:
URL ourLoc = obj.getClass().getResource(className);
 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually not className but className + ".class":

You will need to cut off the starting jar: and everything from the ! on.

Please know that this may not work all of the time, especially if the URL is not a JAR file or folder. Custom class loaders may also mess up this approach.
[ August 05, 2008: Message edited by: Rob Prime ]
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.getProperty("user.dir") will give you the directory where the jar is located.
 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not necessarily. It will return the directory where the application is started. When shortcuts with custom paths are used, or the JAR file is included in the classpath, then it may be different.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doh!
I hadn't thought of that!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!