I have a function that should get the path of a file typed in the textinput of a jfilechooser and pass it to a String. The problem is that I want to check for overwrite if the file exists already. I do have a clue about how to do this, my problem, though, is that, if answering no to the JOptionPane, the JFileChooser closes anyway, because the save button has already been actioned. Now, what I need is that if the answer is no, the program returns to the JFileChooser, still prompting for a name.
Please note that I am searching for an efficient solution, I've already considered executing the function again, but since my program is quite a large one, this way of solving things would cost time and would not be efficient.
Here is the code of my function, yet not completed because I don't know how to handle it.
`public String FileSavePath()throws NullPointerException
{
File f=null;
String theFilepath=null;
JFileChooser FileChooser = new JFileChooser();
if(FileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
theFilepath=FileChooser.getSelectedFile().getAbsolutePath();
f=FileChooser.getSelectedFile();
//System.out.println(theFile);
if(f.exists())
{
int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?",
"Existing file",JOptionPane.YES_NO_CANCEL_OPTION);
if(result==JOptionPane.YES_OPTION)
{
return theFilepath;
}
else // here is what I should do if the user answers 'no' or cancels/closes the JOptionPane
}
else return null;
return theFilepath;
}`
You need to place your query into a loop until such time as the user can provide you with an acceptable response...
public String FileSavePath() throws NullPointerException {
boolean acceptable = false;
String theFilepath = null;
do {
theFilepath = null
File f = null;
JFileChooser FileChooser = new JFileChooser();
if (FileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
theFilepath = FileChooser.getSelectedFile().getAbsolutePath();
f = FileChooser.getSelectedFile();
//System.out.println(theFile);
if (f.exists()) {
int result = JOptionPane.showConfirmDialog(this, "The file exists, overwrite?",
"Existing file", JOptionPane.YES_NO_CANCEL_OPTION);
if (result == JOptionPane.YES_OPTION) {
acceptable = true;
}
} else {
acceptable = true;
}
} else {
acceptable = true;
}
} while (!acceptable);
return theFilepath;
}
Related
I'm working on a program that opens up the JFileChooser and allows the user to choose a .txt file which contains information like name, height, and weight.
The program then calculates the BMI for each person listed in the file and displays them in a JOptionPane. They can then decide whether to choose another file or cancel the program.
I have everything figured out for the calculations and displaying them, but the difficulty I'm having is with the JOptionPane choices. I want to display a message whenever the user chooses the "no" option or when they cancel choosing a file, but I seem to not be able to do so. I'm also unsure how to reopen the JFileChooser whenever they choose the "yes" option. If anyone could provide some guidance on how to achieve this or even what I may be doing wrong, I would greatly appreciate the help. Thank you in advance! This is my code thus far:
public static void main(String[] args) throws FileNotFoundException, IOException {
readFile();
}
public static int readFile() throws FileNotFoundException, IOException {
int choice = (JOptionPane.YES_OPTION);
while (choice == (JOptionPane.YES_OPTION)) {
File file;
JFileChooser fileChooser;
fileChooser = new JFileChooser();
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 300);
int returnVal = fileChooser.showOpenDialog(null);
while (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
String report = BMIRecord.report(file);
int dialogResult = JOptionPane.showConfirmDialog(null, report + "\n\nWould you like to try another file?", "BMI Calculations", JOptionPane.YES_NO_OPTION);
return choice;
}
}
while (choice == (JOptionPane.NO_OPTION)) {
JOptionPane.showMessageDialog(null, "Session ended.");
return choice;
}
return 0;
}
All the loops are confusing the issue. You only need a single loop, the way that prompts the user for a new file and prompts the user to continue...
Basically, you need to prompt for a file, if the JFileChooser returns with JFileChooser.APPROVE_OPTION, you calculate the BMI and display the report and can then prompt the user for another file. Otherwise, you can probably assume they've chosen not to continue.
You keep doing this until JOptionPane.showConfirmDialog becomes equal to JOptionPane.NO_OPTION (or the user cancels the JFileChooser, which is probably the same thing)
Something like...
public static int readFile() throws FileNotFoundException, IOException {
JFileChooser fileChooser = new JFileChooser();
int choice = JOptionPane.NO_OPTION;
do {
choice = JOptionPane.NO_OPTION;
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
String report = BMIRecord.report(file);
choice = JOptionPane.showConfirmDialog(null, report + "\n\nWould you like to try another file?", "BMI Calculations", JOptionPane.YES_NO_OPTION);
}
} while (choice == JOptionPane.YES_OPTION);
return 0;
}
For example...(ps, I'm not sure what the method is "suppose" to return, so I just returned 0)
Looks like your two while loops, after the first while loop, should be if statements. Also, don't return choice. Instead, have it receive the result from JOptionPane.showConfirmDialog().
public static int readFile() throws FileNotFoundException, IOException
{
int choice=(JOptionPane.YES_OPTION);
while(choice == (JOptionPane.YES_OPTION))
{
File file;
JFileChooser fileChooser;
fileChooser = new JFileChooser();
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 300);
int returnVal = fileChooser.showOpenDialog(null);
// If statement, instead of while
String report = "";
if (returnVal == JFileChooser.APPROVE_OPTION)
{
file = fileChooser.getSelectedFile();
report = BMIRecord.report(file);
}
// Ask for another file regardless of the result of the fileChooser
choice = JOptionPane.showConfirmDialog(null, report + "\n\nWould you like to try another file?","BMI Calculations",JOptionPane.YES_NO_OPTION);
}
// If statement, instead of while. Also, this if isn't really needed. Once the while loop exits, the NO_OPTION is implied to have been selected.
if (choice == (JOptionPane.NO_OPTION))
{
JOptionPane.showMessageDialog(null, "Session ended.");
}
return 0;
}
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 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.
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;
}
}
}
I have a program that takes a screenshot of my gui. It automatically saves the .gif file to the eclipse project directory. What I would like is to have it asking a user where to save the image. Basically so the user can browse the file directory and choose the directory.
Here's the code I have:
public void actionPerformed(ActionEvent event) {
try{
String fileName = JOptionPane.showInputDialog(null, "Save file",
null, 1);
if (!fileName.toLowerCase().endsWith(".gif")){
JOptionPane.showMessageDialog(null, "Error: file name must end with \".gif\".",
null, 1);
}
else{
BufferedImage image = new BufferedImage(panel2.getSize().width,
panel2.getSize().height, BufferedImage.TYPE_INT_RGB);
panel2.paint(image.createGraphics());
ImageIO.write(image, "gif", new File(fileName));
JOptionPane.showMessageDialog(null, "Screen captured successfully.",
null, 1);
}
}
catch(Exception e){}
I would use a file chooser dialog instead of a JOptionPane. Here is a link for the tutorial.
Example:
First of all you have to declare JFileChooser object in your class and initialize it.
public Class FileChooserExample{
JFileChooser fc;
FileChooserExample(...){
fc = new JFileChooser();// as a parameter you can put path to initial directory to open
...
}
Now create another method:
private String getWhereToSave(){
int retVal = fc.showSaveDialog(..);
if(retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
return file.getAbsolutePath();
}
return null;
}
This method returns to you the absolute path which user selected. retVal indicates which button was pressed (Save or Cancel). And if it was pressed Save then you handle the selected file.
Then you have this method you can incorporate this with your code. Instead of this line:
String fileName = JOptionPane.showInputDialog(null, "Save file", null, 1);
Write:
String fileName = getWhereToSave();