Displaying Dialogs with JOptionPane
JFileChooser creates file dialogs that let a user choose a file for reading or writing instead of typing a path.
Choosing a File Without Typing a Path
Many programs need a file, but the program cannot know in advance which file the user wants. One option is to ask the user to type a full path. JFileChooser offers a different approach: it creates a file dialog that lets the user browse and choose a file for reading or for writing. This article follows two methods from the same program, readFile() and writeFile(), and traces what happens from the moment the dialog is created to the moment the program decides what to do next.
Before reading further, think about what the program must know after the user closes a file dialog. Does it need the file name only, or does it also need to know whether the user actually picked a file? Write down your guess, then keep reading to check it.
Hints
- Consider what happens if the user clicks Cancel instead of choosing a file.
- The source says both methods check the dialog's return value.
What a JFileChooser Dialog Does
JFileChooser creates file dialogs that let a user choose a file for reading or writing instead of typing a path.
The same class serves both directions of file work. A JFileChooser can be used to pick a file the program will read and to pick a file the program will write. What changes between the two uses is which method the code calls to show the dialog, and how the dialog is set up before it appears. The source's two methods make this visible: readFile() calls showOpenDialog(this), and writeFile() calls showSaveDialog(this).
The source does not expose every detail of the class at this point, and this article does not try to. The goal is to build a picture of the sequence: create the dialog, show it, then decide what to do based on what the user did.
Reusing the Dialog Object
Both methods in the source begin with the same guard: if fileDialog is null, create a new JFileChooser. The variable fileDialog is an instance variable, so it lives on the object rather than inside a single method call. That means the dialog object is created only when it does not already exist, and later calls can reuse it.
fileDialogis an instance variable, so it persists between method calls.- The null check creates the dialog only the first time it is needed.
- The source's comments note that this pattern works inside a GUI component class, because this is passed as the parent of the dialog.
Configuring Reading and Writing Dialogs
The two methods prepare the same kind of object in different ways. The following subsections show each setup in turn, so you can compare the title bar text and the pre-filled file name side by side.
Reading Versus Writing Side by Side
The diagram below places the two setups next to each other. Both use the same class and the same guard, but they differ in the method that displays the dialog, the title, and the file that is pre-selected.
How the Return Value Controls File Code
Showing a dialog does not, by itself, open or write a file. After the user closes the dialog, the method has to decide whether to continue. The source states that both methods check the dialog's return value and return early if the user canceled or closed the dialog. So the file code only runs when the user has approved the dialog. The flowchart below shows this decision.
Tracing two outcomes of the same dialog
The program has just shown the reading dialog. Trace what happens when the user clicks Cancel, and again when the user picks a file and approves.
- 1Outcome A: user cancels
The dialog closes without approval. The return value does not indicate approval, so the method returns early and no file code runs.
- 2Outcome B: user approves
The user picks a file and approves. The return value indicates approval, so the method continues past the check and reaches the file code.
- 3Compare the two
The dialog was shown the same way in both cases. Only the returned value differs, and that value alone determines which branch runs.
The return value is the single point where the program decides whether file code runs. Cancel skips it; approval reaches it.
Checking for an Existing File Before Writing
After the user approves the save dialog, writeFile() calls getSelectedFile() to get the chosen file. It then calls selectedFile.exists() to check whether a file with that name is already present. If it is, the code calls JOptionPane.showConfirmDialog to ask the user whether to replace it. The message includes the file name, and the source's text reads: The file already exists. Do you want to replace it?
getSelectedFile()returns the file the user chose in the dialog.exists()is true when a file with that name is already present.- The confirmation dialog is shown only inside the
exists()branch.
Mistakes Beginners Make with Dialogs
Common mistake Running file code right after showing the dialog without checking the result
What it looks likeCalling a read or write immediately after showOpenDialog or showSaveDialog returns.
Why it failsIf the user canceled or closed the dialog, there is no approved file to work with. The source says both methods return early in that case.
Do this insteadCheck the dialog's return value first, and only continue to file code when the user approved.
Common mistake Using the open-style dialog to pick a file to write
What it looks likeCalling showOpenDialog(this) in a method that saves data.
Why it failsThe source uses
showSaveDialog(this)for writing andshowOpenDialog(this)for reading. The method call is what sets the dialog's purpose.Do this insteadUse showSaveDialog(this) for writing and showOpenDialog(this) for reading.
Common mistake Assuming a file with the chosen name is always overwritten without asking
Why it failswriteFile()callsexists()and, when a file is present, asks the user to confirm replacement withJOptionPane.showConfirmDialog.Do this insteadExpect the existence check and the confirmation prompt before any replacement happens.
Common mistake Assuming the reading dialog starts with a file already chosen
What it looks likeExpecting the user to see a highlighted file the moment the reading dialog opens.
Why it failsreadFile()callssetSelectedFile(null), so no file is initially selected.Do this insteadSet the selected file deliberately when the task needs a starting choice, and use null when a blank start is intended.
Practice: Tracing a Dialog Method
A method sets the dialog title to Select File for Writing, pre-selects a file named output.txt, and shows the dialog with showSaveDialog(this). The user clicks Cancel. Without looking back at the article, describe which lines run, which file code is skipped, and whether the existence check runs. Then explain what would change if the user approved and picked a file that already exists.
Hints
- Ask whether the return value indicates approval.
- The existence check happens after the user approves and
getSelectedFile()is called. - A cancel means the method returns early before reaching
getSelectedFile().
Key Takeaways
JFileChoosercreates file dialogs so a user can choose a file for reading or writing instead of typing a path.- Reading uses
showOpenDialog(this)with the title Select File for Reading and no preselected file; writing usesshowSaveDialog(this)with a default name ofoutput.txtand the title Select File for Writing. - Both methods check the dialog's return value and return early if the user canceled or closed the dialog, so file code runs only after approval.
- In
writeFile(),selectedFile.exists()decides whetherJOptionPane.showConfirmDialog asks the user to confirm replacing an existing file. - The source's diagram stops before showing what happens after the user answers the confirmation, so that outcome should be checked in the full code.