JFilechooser exit on close - java

In my java application, there is a browse button. When browse button is clicked, popup a file chooser to select a file. When I close the file chooser by clicking cross mark at the top right corner without selecting a file, it gives an Exception saying "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException". How shall I prevent this error?
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
//chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
//chooser.setAcceptAllFileFilterUsed(false);
chooser.showOpenDialog(frame);
path=chooser.getSelectedFile().getPath();

If you exit the JFileChooser without selecting a file, chooser.getSelectedFile() will return null.
Therefore, on your line path=chooser.getSelectedFile().getPath(); you are getting a NullPointerException when you try to call getPath() on the null selected file, since you exited.
You will need to do some error handling, such as this:
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.showOpenDialog(frame);
File selectedFile = chooser.getSelectedFile();
if (selectedFile == null) {
System.out.println("No file selected!");
path = "";
}
else {
path = selectedFile.getPath();
}
In situations like this, I'd recommend reading through the Javadoc of the method you're retrieving resources from. Quite often under the "returns" section it will state if the returned object can be null, or even if it is guarenteed not to be null.
It helps me a lot when deciding when and when not to add things like null checking.

Probably the best way to go with JFileChooser is using chooser.showOpenDialog(this), which returns a value that indicates what the user clicked.
Instead of
chooser.showOpenDialog(frame);
you can write
int returnVal = chooser.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
path=chooser.getSelectedFile().getPath();
// whatever other code that only has sense if the user clicked "Ok".
}
And now you understood it, the usual faster way:
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { //whatever }
You can take a look at the other few values chooser.showOpenDialog() can return, but this is usually enough.

Related

Java open folder does return the selected folder

I use the following code I found on internet to select a folder:
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Select destination folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
jTextField2.setText(chooser.getCurrentDirectory().getAbsolutePath());
} else {
System.out.println("No Selection ");
}
However if for example I browse to
"C:\testfolder\"
then the
"chooser.getCurrentDirectory().getAbsolutePath()"
returns
c:\
How can I resolve this to return "C:\testfolder\" ?
Use chooser.getSelectedFile() instead of chooser. getCurrentDirectory(). You might want have a look at How to Use File Choosers for more details.
You not asking the dialog for the currently selected file, but where the dialog was set to start from

How to set the last path as the next default using JFileChooser

I have several dialog boxes which provide a File Chooser. For the first, my coding was like this
JFileChooser chooser= new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal= chooser.showOpenDialog(this);
if(returnVal==JFileChooser.APPROVE_OPTION){
File f= chooser.getSelectedFile();
jTextField1.setText(f.getPath());
chooser.setCurrentDirectory(f);
}
In my case, i would like to set the last path which is selected as the default path in next selection JFileChooser. Is there any solution for me?
Thanks for any response
Depending on your requirements, you can use Preferences to store it away and use it again after the program has been restarted.
Preferences pref = Preferences.userRoot();
// Retrieve the selected path or use
// an empty string if no path has
// previously been selected
String path = pref.get("DEFAULT_PATH", "");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Set the path that was saved in preferences
chooser.setCurrentDirectory(new File(path));
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File f = chooser.getSelectedFile();
chooser.setCurrentDirectory(f);
// Save the selected path
pref.put("DEFAULT_PATH", f.getAbsolutePath());
}
You will have to "remember" the last path.
This can easily be done by storing the value in a instance variable...
private File lastPath;
//...
lastPath = f.getParentFile();
And simply resetting it when you need to...
//...
if (lastPath != null) {
chooser.setCurrentDirectory(lastPath);
}
You could also use a single instance of the JFileChooser, so each time you show it, it will be at the last location it was used...

Swing - JFileChooser open dialog does not show images for various options

I'm using JFileChooser API for opening a file. When open dialogbox appears, it does not show images for various option like, Up one lever, Create new Folder, List, Details. Some of the option is also not visible untill mouse hover. Here is the image :
My code looks something like this:
JFileChooser fileChooser = new JFileChooser();
FileFilter xlsExcelType = new FileNameExtensionFilter("Excel spreadsheet (.xls)", "xls");
FileFilter xlsxExcelType = new FileNameExtensionFilter("Excel spreadsheet (.xlsx)", "xlsx");
fileChooser.addChoosableFileFilter(xlsExcelType);
fileChooser.addChoosableFileFilter(xlsxExcelType);
fileChooser.setFileFilter(xlsxExcelType);
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file= fileChooser.getSelectedFile();
}
Kndly pass your idea to make those option visible with image.
Thanks
Look and see if java.awt.FileDialog has the option(s) you want. If not, you might try ideas from here or here.

Using JFileChooser without opening the actual file

I'm using the JFileChooser to allow a user to choose a .txt file that will later be processed by my program, however when the user chooses the file, it is actually opened by my computers default app (in my case TeXworks) as well as used by my program. Any idea how I can stop this?
File fileToOpen = fileChooser.getSelectedFile();
JFileChooser's getSelectedFile() method, returns a File object.
Use the getAbsolutePath() to get the absolute name to the file.
Modified example from the JavaDoc:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open this directory: " + chooser.getSelectedFile().getAbsolutePath());
}
So in your case you just need to append .getAbsolutePath() to the end of your statement, like this:
File fileToOpen = fileChooser.getSelectedFile().getAbsolutePath();

showOpenDialog() again if opened file is not XML

I made a simple application to open only XML files using JFileChooser. How can I show the open dialog again and again until I open correct XML file or press cancel button?
You could add a file filter to the file chooser that checks whether the file is an xml file.
When the user has selected a file you check that file's content and if it isn't valid you just open the filechooser again, e.g. in a loop that exits when either the file is valid or the user selected the cancel option.
Basically the loop might look like this (that's quickly written and might contain errors):
int option = CANCEL_OPTION;
boolean fileIsValid = false;
do {
option = filechooser.showOpenDialog(); //or save?
if( option == OK_OPTION ) {
fileIsValid = isValid( filechooser.getSelectedFile()); //implementation of isValid() is left for you
}
} while( option == OK_OPTION && !fileIsValid);
This loop does the following:
it opens the filechooser and gets the selected option
when the OK option is selected the selected file is checked
when the OK option was selected but the selected file is invalid, do another iteration - otherwise end the loop (if another option, e.g. CANCEL, was selected or the file is valid)
Keep opening the dialog until cancel is pressed or a valid file is chosen. You have to implement isValidFile yourself:
do {
int returnVal = chooser.showOpenDialog(parent);
} while (returnVal != JFileChooser.CANCEL_OPTION || !isValidFile(chooser.getSelectedFile()));
What about this Solution:
It open filechooser and checks if it was not a CANCEL_OPTION. If your check for the correct XML File was successful, then you break the while loop.
JFileChooser fc = new JFileChooser();
int returnVal = -1;
while (returnVal != JFileChooser.CANCEL_OPTION) {
returnVal = fc.showOpenDialog(putYourParentObjectHere);
if (returnVal == JFileChooser.APPROVE_OPTION) {
if (doYourCheckIfCorrectXMLFileWasChosenHere) {
// do the stuff you want
break;
}
}
}

Categories