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;
}
}
}
Related
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...
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.
I have two seperate methods of opening a file.
The first uses a FileChoser with an additional file type filter.
JFileChooser inFileName = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("PCF & TXT Files", "pcf", "txt");
inFileName.setFileFilter(filter);
Component parent = null;
int returnVal = inFileName.showOpenDialog(parent);`
The second uses a JOptionPane but has a loop to ensure the directory chosen exists
String filePath;
File directory;
do{
filePath = JOptionPane.showInputDialog("please enter directory");
directory = new File(filePath);
if (directory.exists()==false){
JOptionPane.showMessageDialog(null,"error with directory");
}
}while(directory.exists()==false);
I'm looking to get the best of both here. To be able to choose a file, using a file filter and also loop that function should that directory not be valid.
I've tried switching around variable names and the various functions in different places but I cant seem to get the loop (".exists" function) to work.
You just need to modify your JFileChooser code to use a loop.
JFileChooser inFileName = new JFileChooser();
File file;
boolean valid = false;
while (!valid) {
int returnVal = inFileName.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = inFileName.getSelectedFile();
valid = file.isDirectory();
else {
valid = returnVal == JFileChooser.CANCEL_OPTION;
}
}
Its worth mentioning that this kind of thing might be better achieved using;
jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
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();
I would build a panel which let me choose where I can save a file. I read java documentation and I saw that there is a swing component named file chooser but I don't know how use it.what i want to do is choose the path in my machine where saved a file created.
How to use it? Well, you just need to "use it"! Really!
This will create your FileChooser instance and set it to start at user's desktop folder:
JFileChooser fc = new JFileChooser(System.getProperty("user.home") + "/Desktop");
After that, you can set a variety of options. In this case, i'm setting it up to allow choosing multiple files, and only ".xls" (Excel) files:
fc.setMultiSelectionEnabled(true);
SelectionEnabled(true);
FileFilter ff = new FileFilter() {
#Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = f.getName().substring(f.getName().lastIndexOf("."));
if (extension != null) {
if (extension.equalsIgnoreCase(".xls")) {
return true;
} else {
return false;
}
}
return false;
}
#Override
public String getDescription() {
return "Arquivos Excel (\'.xls\')";
}
};
fc.setFileFilter(ff);
And finally, i'm showing it up and getting the user's choice and chosen files:
File[] chosenFiles;
int choice = fc.showOpenDialog(fc);
if (choice == JFileChooser.APPROVE_OPTION) {
chosenFiles = fc.getSelectedFiles();
} else {
//User canceled. Do whatever is appropriate in this case.
}
Enjoy! And good luck!
This tutorial, straight from the Oracle website, is a great place to start learning about FileChoosers.
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + ".");
} else {
log.append("Open command cancelled by user.");
}
The above code opens a FileChooser, and stores the selected file in the fc variable. The selected button (OK, Cancel, etc) is stored in returnVal. You can then do whatever you wish with the file.