I am currently trying to use JFileChooser to return the path of a file or directory as a string. However, I found that I cannot choose a folder as my selection until I choose a file first. While this isn't a major issue it is by far frustrating to solve.
Gfycat of what is happening: https://gfycat.com/DeadlyDeliriousAzurevase
Code:
public static String openFileChooser()
{
int returnValue = fileChoose.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION)
{
fileChoose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
return (fileChoose.getSelectedFile().getAbsoluteFile().toString());
}
else
{
return "null";
}
}
Help would be absolutely appreciated, thank you!
You're setting the file selection mode after you've shown the dialog and the user has clicked the button. It won't have any effect at that point. You need to set it before you show the file chooser dialog.
The line you need to move up to be the first line in your method is:
fileChoose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
You should change your code to
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(fileChooser.getSelectedFile().getAbsoluteFile().toString());
} else {
System.out.println("Empty");
}
make sure invoke
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
before you open your dialog
Related
I have code that is supposed to choose a folder from a JFileChooser, but it still is acting like its choosing a file, even if I use fs.setDialogType. I tried showSaveDialog and showOpenDialog, but they both don't work.
Here is my code:
public static String getFolder() {
JFileChooser fs = new JFileChooser();
fs.setDialogType(JFileChooser.DIRECTORIES_ONLY);
fs.showSaveDialog(null);
if (fs.getSelectedFile() != null)
return fs.getSelectedFile().getAbsolutePath();
return "null";
}
setDialogType is used to set the open, save or custom type for the dialog. Use setFileSelectionMode to specify the whether the dialog should select files or directories
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
is it possible to make a JFileChooser which can choose a file or a directory?
Because, if I use a filefilter in my chooser it is only possible to choose the files included the filter option, but I am no longer able to choose a directory.
this is my JFileChooser
JFileChooser ch = new JFileChooser();
ch.setAcceptAllFileFilterUsed(false);
ch.setFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f != null && f.isDirectory()) {
return true;
}
if (f == null || !f.getName().toUpperCase().endsWith(".PROPERTIES")) {
return false;
}
return true;
}
public String getDescription() {
return "Property Files" + " (*.properties)";
}
});
ch.setCurrentDirectory(new File("."));
ch.showOpenDialog(this);
if (ch.getSelectedFile() != null) {
ressource = ch.getSelectedFile();
}
else {
return;
}
txtRessource.setText(ressource.getAbsolutePath());
Just call
ch.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
And that way you will be able to select either a file or a directory. This works with combination of your filter.
Btw you don't have to implement the file filter too, there is a FileNameExtensionFilter which does exactly what you want (it also accepts folders):
ch.setFileFilter(new FileNameExtensionFilter("Properties file", "properties"));
To select files and directories try this
file_chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
And to choose only directories try this
dir_chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
REASON
As the name suggests, adding a file filter will only filter out a ceratin types of files and will allow you to choose only particular type of file like .jpg,.png etc if you want to select only image files. But to select a directory or only a file you have to set the file selection mode of the JFileChooser instance. Set the mode according to your requirements.
Dude was looking for the answer of this as well. I think its too late to tell you, but for anyone looking I think adding file.isDirectory() == true on the filter work. So in this case if you are looking to choose files ending with .Properties then
public boolean accept(File f) {
if (f.isDirectory() || f.getName().toUpperCase().endsWith(".PROPERTIES")) {
return true;
}
So in this case if its either a file directory or something that ends with a properties extension
I am exploring Jfilechooser.I already get the file path in the Jfilechooser.Now I want to display the information like file name, file size, location, and access rights.Is their anyway to display those information using the file path only.Anyone can help me?I want it to display in a TextArea.
this is the how I pop up a Jfilechooser.
private void browsebuttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
fieldlocation.setText(filename);
}
Take a look at the JavaDoc for File:
File.getName()
Will return the name of the file
File.length()
Will return the size of the file in bytes
File.getAbsolutePath()
Will return the absolute path of the file
File.canRead()
File.canWrite()
File.canExecute()
Will return your access rights on the file.
One thing I would note about your code is that you don't check the return value from the file chooser. If the user clicks cancel you probably want to abort processing. The way to do this is to check the return value of JFileChoose.showOpenDialog(null); like so:
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Straight from the JavaDoc.
In short I would suggest that you (re)?read the documentation for the APIs you are using. It will save you much time in the long run if you understand your own code.
I'm working on a Halo: CE custom game launcher in Java, and I'm setting up a preferences system using the Properties class in Java, so the user can set custom game paths. I use a JFileChooser to select a file and then write that path to the config file.
But, the program gives a Null Pointer Exception at this line: (This is in the event listener function)
if(source == fovChooseButton)
{
int returnVal = chooseFile.showOpenDialog(settingsWindow);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File selected = chooseFOV.getSelectedFile();
try
{
config.setProperty("STLPath", selected.getAbsolutePath()); //This line gives the exception
config.store(new FileOutputStream(CONFIG_FILE), null);
}
catch(Exception e)
{
handleException(e);
}
}
}
I do have another JFileChooser, and it does not throw any exceptions. Here's the code for the other one:
if(source == fileChooseButton)
{
int returnVal = chooseFile.showOpenDialog(settingsWindow);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File selected = chooseFile.getSelectedFile();
try
{
config.setProperty("GamePath", selected.getAbsolutePath());
config.store(new FileOutputStream(CONFIG_FILE), null);
}
catch(Exception e)
{
handleException(e);
}
} // end if
}
All handleException() does is display a dialog window with the stack trace.
Help?
Your prompting the User for a file with chooseFile afterwards you are trying to read the file from the other filechooser chooseFOV
int returnVal = chooseFile.showOpenDialog(settingsWindow);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File selected = chooseFOV.getSelectedFile();
What's chooseFOV ? You seem to be using chooseFile for the dialog, so it's the one that's got a selection.
int returnVal = chooseFile.showOpenDialog(settingsWindow);
File selected = chooseFOV.getSelectedFile();
You have two variables and probably want to use chooseFile on the second line as well.
I have this program where u can download files and i want the JFileChooser to be locked to one folder(directory) so that the user cant browse anything else. He can only choose files from for example the folder, "C:\Users\Thomas\Dropbox\Prosjekt RMI\SERVER\". I have tried so search but did not find anything.
The code I have is:
String getProperty = System.getProperty("user.home");
JFileChooser chooser = new JFileChooser(getProperty + "/Dropbox/Prosjekt RMI/SERVER/"); //opens in the directory "//C:/Users/Thomas/Dropbox/Project RMI/SERVER/"
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
And this is working fine, but now i can go to the folder Project RMI, that i don't want it to do.
Thanks in Advance :)
Edit: What I did with your help:
JFileChooser chooser = new JFileChooser(getProperty + "/Dropbox/Project RMI/SERVER/");
chooser.setFileView(new FileView() {
#Override
public Boolean isTraversable(File f) {
return (f.isDirectory() && f.getName().equals("SERVER"));
}
});
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: "
+ chooser.getSelectedFile().getName());
}
Set a FileView and override the isTraversable method so that it returns true only for the directory you want the user to see.
Here is an example:
String getProperty = System.getProperty("user.home");
final File dirToLock = new File(getProperty + "/Dropbox/Prosjekt RMI/SERVER/");
JFileChooser fc = new JFileChooser(dirToLock);
fc.setFileView(new FileView() {
#Override
public Boolean isTraversable(File f) {
return dirToLock.equals(f);
}
});
Make a custom FileSystemView, use it as the argument to one of the JFileChooser constructors that accepts an FSV..
In my case I needed to disable both directory navigation and choosing a different file extension Here's another approach for posterity: a small recursive method to disable the navigation controls:
private void disableNav(Container c) {
for (Component x : c.getComponents())
if (x instanceof JComboBox)
((JComboBox)x).setEnabled(false);
else if (x instanceof JButton) {
String text = ((JButton)x).getText();
if (text == null || text.isEmpty())
((JButton)x).setEnabled(false);
}
else if (x instanceof Container)
disableNav((Container)x);
}
Then call as follows:
JFileChooser fc = new JFileChooser(imgDir);
disableNav(fc);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif", "png");
fc.setFileFilter(filter);
...