Understanding JFileChooser behaviour - java

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.

Related

JFileChooser: Save the last directory user navigates to before cancelling

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

running external exe with spaces in java

I have been trying for 4 hours now to get this thing to run and I managed to do it without understanding why :/
I have created a very simple java program with a GUI containing 2 textboxes where people can type the path to an exe-file.
When a button is clicked it reads the text in this box and runs the corresponding software.
This seems to work when people type ""C:\Program Files (x86)\thatsoftware\" in the directory box and "C:\Program Files (x86)\thatsoftware\run this.exe -arg" in the file to run box:
Runtime.getRuntime().exec(txtFile.getText().toString(), null, new File(txtPath.getText().toString()));
However, when I set only 1 directory box and append (hardcoded) the file and argument to it, it will not work:
String fileToRun=txtPath.getText().toString()+"run this.exe -arg";
Runtime.getRuntime().exec(fileToRun, null, new File(txtPath.getText().toString()));
I have tried passing the file as an array as well:
String fileToRun[]={txtPath.getText().toString(),"run this.exe"," -arg"};
Runtime.getRuntime().exec(fileToRun, null, new File(txtPath.getText().toString()));
to no avail.
The same kind of problems pop up when I try to run it as a processbuilder.
I will get an error message like "file C:\Program Files (x86)\thatsoftware\ -arg" does not exist." Very weird, since the argument is passed, but not the file name apparently.
I can manage to run it when the whole string is typed in the text box by the user, but not if I add the argument and or filename to it in the code.
Could anyone be so kind to explain this to me and tell how it can be done with only one text box?
As I know you must put each element as separate field:
String fileToRun[]={
txtPath.getText().toString(),
"run",
"this.exe",
" -arg"
};
I don't know if you use Swing or not but Swing has javax.swing.JFileChooser.
//config fileChooser
JFileChooser fc = new JFileChooser(lastOpenDir);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setDialogTitle("Load Beacon List");
fc.removeChoosableFileFilter(fc.getFileFilter()); //remove the default file filter
FileFilter filter = new FileNameExtensionFilter("EXE file", "exe");
fc.addChoosableFileFilter(filter); //add XML file filter
//show dialog
int returnVal = fc.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File selectedDir = fc.getSelectedFile();
...
You need to wrap the executable in escaped quotes \" like this:
Runtime runtime = Runtime.getRuntime();
Process ps = runtime.exec("\"run this.exe\"");
Or using a path and the argument as you need:
Process ps = runtime.exec("\"C:\\Program Files (x86)\\Thatsoftware\\my exe.bat\" -arg");
boy do i feel like an idiot...
The java errors threw me off, but the problem was a missing slash before "run this.exe".
so many shames...

JFileChooser change default directory in Windows

I want to change the default directory of my JFileChooser to "My Music" on Windows.
This directory is C:\Users\Fre\Music on my account because my username is Fre
The default is set on C:\Users\Fre\Documents (depends on OS i think).
How can I change this?
You can use the API method setCurrentDirectory when initializing your JFileChooser objects:
public void setCurrentDirectory(File dir)
Sample usage might be like:
yourFileChooser.setCurrentDirectory(new File
(System.getProperty("user.home") + System.getProperty("file.separator")+ "Music"));
why don't you just give the FileChooser the path when you create it, like:
JFileChooser chooser = new JFileChooser("C:\\Users\\Fre\\Music\\");
Sorry for taking your time,
Just found the answer myself:
String userhome = System.getProperty("user.home");
JFileChooser fc = new JFileChooser(userhome +"\\Music");
JFileChooser openFile = new JFileChooser("C:\\Users\\Fre\\Music");
Creating all your own code, so as to set a default file directory is unnecessary and lengthy. A much easier and quicker way of doing it is by just right clicking on the File Chooser itself on Design view and right clicking 'customise code'.
Customise Code for File Chooser
This will show you the vital code for that GUI component. From the drop down box next to the top line of code, select 'custom creation'.
This will allow you to customise what fileChooser = is assigned to. Between the curly brackets JFileChooser() you can either hard code in the file directory with speech marks like this.
JFileChooser("C:\Users\user\Documents")
or type in a name that for a variable you created earlier. This variable would hold the file directory. I would recommend the latter option, though either will work fine.
Hope this helps.
p.s. sorry about having to use a link for the photo. I don't have enough privilege yet.
You can Change the default directory of my JFileChooser to "Directory you want" on Windows
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("put here your directory"));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
jTextField.setText(selectedFile.getAbsolutePath());
}
Pretty Simple:
JFileChooser browseImageFile = new JFileChooser("User Defined Directory");

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.

Categories