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.
Related
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.
Hi I am trying to make one pane that shows something like windows explorer in my computer.
when user complete it's operations, and after that when he want to save edited image at specific place on disk then he can easily select directory from that pane.
i want to design something like this :
is it possible to do something like that ?
my picture editor looks like :
at right side of editor i want to put something like output directory selection pane.
is anyone know how to do that ?
A complete example using JTree is examined in FileBrowser.
An alternative using Outline is shown here.
Yes its possible. It's basically just JTree.
You will probably want to take a look at File#listRoots, File#isDirectory and File#listFiles.
You'll also want to take a look at How to use trees.
You'll probably also want to take a look at FileSystemView#getSystemIcon which will allow you to look an appropriate icon for the given File
However, it might be simpler to just use a JFileChooser ;)
You could have a look at JFileChooser.
You can use this object to open a SaveDialog and get a save path on the local harddisk.
Then eventually use an ObjectOutputStream to write a file.
Sample code:
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Demonstrate "Save" dialog:
int rVal = c.showSaveDialog(fb);
if (rVal == JFileChooser.APPROVE_OPTION) {
System.out.println(c.getSelectedFile().toString());
}
This can be handled with a JFileChooser, sorry if it's not the solution you're looking for
Note: you say choose a directory but I assume you mean that they can name their file
private File selectSaveFile() {
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("File Type", "txt"));
fc.setCurrentDirectory(new File(System.getProperty("user.home")));
int returnVal = fc.showSaveDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
}
//the user didn't click save if we are here
return null;
}
i want to ask you regardless finding the file path...
I have, or i would have files that will be associated with my app, but i dont know how to find out the file path that initializes opening my app.
For example:
If i click in windows enviroment on excel file "file.xlx", windows will open excel application with this file "file.xls" and i want exactly the same. After my app will be open, i want to know file path that inicializes my app to start...
I hope that my question is understandable and i apologize for my bad english.. :)
Edit:
I try add some another example...
I try describe some logic operations...
1 - nothing is running, only windows - i hope :)
2 - user click on some file that is somewhere in the HDD ( this file can have different name and different location )
3 - this file with some extension has associated start with my app
4 - app automatically find out on whitch file user clicked ( who invoke the launch of my application ) and use this file path on other work...
I think that should be something like when i start console app. with some argument....but this argument i must get from some windows location.
Just like when i click on file.txt and windows will open notepad and notepad will have automatically open this file.txt, or i click on file.dbf and windows will open the foxpro with this file
I want click on file.xxx and my app will open and work with this file automatically, so there i think must be some way how to get this file location on which i clicked...
I hope this help...
Look at the java system properties http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html, you probably want user.dir
i think what you need is a program like this , this will calculate the existance of your file in side the given directory
package fileSearch;
import java.io.File;
import java.io.FilenameFilter;
public class fileSearch {
/**
* #param args
*/
public static void main(String[] args) {
fileSearch obj = new fileSearch();
obj.finder("program.txt");
for(int i=0;i<obj.finder("C:/Users/hussain.a/Desktop").length;i++)
{
System.out.println(obj.finder("C:/Users/hussain.a/Desktop")[i].getName());
}
}
public File[] finder( String dirName){
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename)
{ return filename.endsWith(".txt"); }
} );
}
}
now its up to you to apply to your desired directory , if you want it to exactly like the windows program , then you will have to use root directory every time and pass the file name as a parameter replacing ".txt" in this program
hope it serves , rest is up to you to implement it
I think you can set the os,like the registry,when you installing the app.
String osName = System.getProperty("os.name") ;
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");
I am using Netbeans for java application. during my application at one point i want particular folder URL to store files. how can i achieve this. please can anyone help me..
Thanks in advance :)
Use a JFileChooser, with JFileChooser.DIRECTORIES_ONLY Take a look at this tutorial: How to Use File Choosers
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
You want to select a folder in a swing application, right? you can use JFileChooser http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
to select only a folder, look at this example
http://www.rgagnon.com/javadetails/java-0370.html
for the saving, check
http://download.oracle.com/javase/tutorial/essential/io/file.html
if you need something clarified, just ask.
I guess you want a Open File Dialog box.
In Swing it is called JFileChooser.
Usage example:
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(yourJFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
// Do stuff with file
} else {
// User clicked cancel
}
yourJFrame should be the JFrame you use for your main window. If you don't have one put null.