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;
}
Related
The code works to check for non-empty/whitespace AbsolutePath, but not when the AbsolutePath is simply blank. Clicking save does nothing and the JFileChooser stays in showSaveDialog().
I want to show a JOptionPane error message when the user attempts to save the file with an empty-whitespace file name.
try {
JFileChooser chooser = new JFileChooser("./");
FileNameExtensionFilter filter = new FileNameExtensionFilter("files (txt)", "txt");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(false);
chooser.setSelectedFile(new File(fileName));
int value = chooser.showSaveDialog(this);
if (value == JFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().getAbsolutePath();
if (chooser.getSelectedFile().getName().trim().equals("")
|| !chooser.getSelectedFile().getName().endsWith(".txt")
|| chooser.getSelectedFile().getName().replaceAll(".txt", "").trim().equals("")) {
throw new IllegalArgumentException();
}
saveFile(filename);
}
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(this, "Fail! File was not saved", "Error", JOptionPane.ERROR_MESSAGE);
}
Clicking save does nothing and the JFileChooser stays in showSaveDialog(). as #camickr said above: this is the built in functionality of the JFileChooser and has nothing to do with your code. The file chooser doesn't close unless you enter a filename (and click Save) or use the Cancel button..
export content to an xls file using java with save dialog:
- Where should I ask for a file name during save?
I prefer to ask what to name the file when it is saved.
public static void main(String args[])
{
SaveToExcel exp = new SaveToExcel();
exp.writePropertiesIntoExcel("D:\\ExcelFile.xls");
}
You should use JFileChooser if you want to let the users choose where to save the file.
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.APPROVE_OPTION);
chooser.setMultiSelectionEnabled(false);
int returnVal = chooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION){
File f = chooser.getSelectedFile();
String a = f.getAbsolutePath();
SaveToExcel exp = new SaveToExcel();
exp.writePropertiesIntoExcel(a);
}
A simple code you can use in your method, this gets the path you want to save your file in.
Iam a java beginner.
I have written a simple program to write some contents to a file using showSaveDialoge() in JFileChooser. The code including below.
public static void main(String arg[]) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
try {
File file = new File("fileName.txt");
fc.setSelectedFile(file);
int r = fc.showSaveDialog(frame);
if(r == JFileChooser.APPROVE_OPTION)
{
FileWriter writer = new FileWriter(file);
writer.append("Data inside the file");
writer.flush();
writer.close();
}
else if(r == JFileChooser.CANCEL_OPTION) {
System.out.println("Do nothing for CANCEL");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "File could not be written, try again.");
}
}
the code gets executed and Save Dialogue box has come. But when I click SAVE button on Dialogue box, nothing had happening. The file has not saved in the selected location. What may be the reason.?
Thanks in advance.
What is hapenning is:
you create a File in your current location with name fileName.txt
File file = new File("fileName.txt"); //could be $HOME$/fileName.txt
User selects ProgramFiles/file.txt
but you uses on FileWritter file information, not what user chossed from FileChooser.
change
FileWriter writer = new FileWriter(file);
to
FileWriter writer = new FileWriter(chooser.getSelectedFile());
Try this:
FileWriter writer = new FileWriter(fc.getSelectedFile());
It should write to selected file from file chooser.
You were writing to fileName.txt which will be saved in current directory from which you run program.
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;
}
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.