JFileChooser: Save the last directory user navigates to before cancelling - java

I'm using JFileChooser to open up a dialog box for a user to open a file. I've already set the current directory if the user actually selects a file:
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File newfile = fc.getSelectedFile();
//set the default directory to this file's directory
fc.setCurrentDirectory(newfile.getParentFile());
}
else {
//User cancels file chooser. How to still set the current directory
//to the one they were last in?
}
However, even if the user cancels the dialog box (e.g. they decide they want to do something else in the program before choosing a file), I want to save the last directory they were in so they avoid the hassle of finding that directory again. Is this possible at all?

This is because an instance of JFileChooser "remembers" it's last location. You could create a new instance each time you want to show the dialog, but that's inefficient and can be time consuming
Instead, save the last "good" location in some kind of instance variable. Before you show the save dialog, set its current directory, passing the last known "good" location

Related

Understanding JFileChooser behaviour

I am trying to open a JFileChooser dialog to let the user decide his wish-directory for following operations.
Following is my current code:
JFileChooser chooser;
if(pref.get("LAST_PATH", "") != null){
chooser = new JFileChooser(pref.get("LAST_PATH", ""));
} else{
chooser = new JFileChooser(home_dir);
}
//chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
int retVal = chooser.showOpenDialog(frame);
System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory().toString());
home_dir is a static String pointing to the users Download-directory.
The behaviour I do not understand:
home_dir = C:/Users/Scy/Downloads
Press OK without selecting any file(Or directory)
Output: C:/Users/Scy
home_dir = C:/Users/Scy/Downloads
Select any file within Downloads
Output: C:/Users/Scy/Downloads
Why do I not get the full-path(C:/Users/Scy/Downloads) as output when not selecting anything and just pressing OK? (With DIRECTORIES_ONLY activated, can't press OK without selecting anything without DIRECTORIES_ONLY)
Edit: I just noticed that when I just press the Cancel button without selecting anything the output is indeed what I expect, C:/Users/Scy/Downloads.
Based on an answer on this post I tried the following:
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(home_dir)); //home_dir = "C:/Users/Scy/Downloads"
The result was exactly the same as above. Pressing the Cancel button results in the full path output, while pressing OK/Accept results in C:/Users/Scy.
Maybe the 'selected file'(or directory) is in the 'current directory' (which you are retrieving atm.)?
If you want the current selected file, chooser.getSelectedFile() is what you are looking for. Keep in mind that when switching to DirectoryOnly mode this method will return a directory (e.g. a File instance representing a directory).
The method chooser.getCurrentDirectory() will return the parent directory of the current selected file which explains the unexpected results. (getSelectedFile.getParentFile() will most likely return the same file)
If you are trying to retrieve the parentDirectory, you set the starting directory incorrect. Notice how you pass in the first constructor a selected File? This means in the second constructor the 'home_dir' will be the selected File. If you only want to set 'home_dir' as starting directory, you should use the no-args constructor and call chooser.setCurrentDirector(new File(home_dir)) instead. Here is a snippit of what your code could look like:
JFileChooser chooser;
if(pref.get("LAST_PATH", "") != null){
// set last SELECTED file/directory path.
chooser = new JFileChooser(pref.get("LAST_PATH", ""));
} else{
// set currentDirectory, but dont select anything yet.
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(home_dir));
}
getCurrentDirectory() returns a directory name, not a file name. If the user selects a file, this method returns the name of the directory which contains that file. If you want the name of the file which was selected, you should use getSelectedFile(). If you haven't yet, you should read this Oracle tutorial on file choosers.

Display a file dialog that prompts only for Eclipse Project File location

How can I arbitrarily display the same file dialog that occurs from New -> File?
I have an Eclipse Action where I wish to display the project file path dialog, and not the system file path dialog, as seen in this image:
Also there is one catch: I want to display existing files too, as I will not be creating a new file, but instead may be overwriting/synchronizing a file. If this is NOT possible, I'll still want to know how to just display the same dialog as is in New -> File.
To display a workspace file picker, you will need to do something along these lines:
ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
shell,
new WorkbenchLabelProvider(),
new WorkbenchContentProvider());
dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
dialog.setAllowMultiple(false);
if (dialog.open() == Window.OK) {
IResource resource = (IResource) dialog.getFirstResult();
}
ElementTreeSelectionDialog is quite customizable, so you can tune the behavior to your needs.

java file chooser that forces the file to already exist

After a bit of googling I'm not seeing this turn up much. Is there some "generic" way to forces the user to select a file that "already exists"
I could add something like
http://coding.derkeiler.com/Archive/Java/comp.lang.java.help/2004-01/0302.html or like JFileChooser with confirmation dialog but is there some canonical way?
Thanks.
First you need to check if your better option is choser.showOpenDialog or showSaveDialog
Save Dialog will let you select any name in the specified path it could be a non existent file, but open will always accept the selected file.. and you can safely add a file.exists() to ensure the file exists. You can also change the text of the buttons.. dialog.. etc..
JFileChooser chooser = new JFileChooser();
chooser.setApproveButtonText("Save");
int result = chooser.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File selection = chooser.getSelectedFile();
//verify if file exists
if(selection.exists()){
//you can continue the code here or call the next method or just use !exists and behavior for wrong file
}else{
//System.exit(0), show alert.. etc
}
}
Sounds like you want an "Open" behavior, but a confirmation button that says "Save" instead of "Open".
You can do this via this method:
http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html#showDialog%28java.awt.Component,%20java.lang.String%29
Pass in "Save" for the approveButtonText argument.
As simple as this:
JFileChooser fc = new JFileChooser();
while(true)
{
if(fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION &&
!fc.getSelectedFile().exists())
JOptionPane.showMessageDialog(null, "You must select an existing file!");
else break;
}

showing predefined file at File Chooser Option in Java Swing

So, i am showing a file chooser dialog using:
JFileChooser c = new JFileChooser();
int rVal = c.showSaveDialog(this);
if (rVal == JFileChooser.APPROVE_OPTION) {
saveFile((c.getCurrentDirectory().toString() + "/" + c.getSelectedFile().getName()), "data to be saved");
}
It works fine, but problem is user himself has to write a file name at the file prompt where file name is to be provided or he can select a file from file listing so that it can be overwritten.
I want to know is there any way that the file chooser text box already shows the users suggested file name so that he simply clicks on save and it works.
Just call setSelectedFile method before showing the dialog.

Java select a file location

I'm not sure if this is even possible as I can't find anything about it after quite a few Google searches.
What I would like to do is on event open up a file dialog box and allow the user to select a folder and then store that folders full directory in a string. So if a user selected a folder in C:\Windows\Example the directory would be stored in String fileDir = C:\Windows\Example;
Does this make sense? I hope so as I'm struggeling to find the answer. I do apperciate the help, thanks in advance for looking and more thanks if you help me :)
In swing you'll want a JFileChooser.
public String promptForFolder( Component parent )
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
if( fc.showOpenDialog( parent ) == JFileChooser.APPROVE_OPTION )
{
return fc.getSelectedFile().getAbsolutePath();
}
return null;
}
It can be a little awkward selecting folders from a user's perspective. I've watched a lot of folks struggle with it. If you have the time you may want to try my DirectoryChooser. Sorry the code is so crufty; I wrote it awhile back.
You are looking for a FileChooser.
File choosers provide a GUI for navigating the file system, and then either choosing a file or directory from a list, or entering the name of a file or directory. To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser.

Categories