Concepts / Displaying Dialogs with JOptionPane

Displaying Dialogs with JOptionPane

JFileChooser creates file dialogs that let a user choose a file for reading or writing instead of typing a path.

  • Programming

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.

EASY

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

Definition

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.

java
Notes on the code
  • fileDialog is 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.

showOpenDialog(this)showSaveDialog(this)Select File forReadingSelect File forWritingNo preselected filesetSelectedFile(null)Preselectedoutput.txtsetSelectedFile(new Fileoutput.txt)
How does the open-style dialog for reading differ from the save-style dialog for writing in method called, title, and pre-selected file?

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.

Show dialogshowOpenDialog orshowSaveDialogUser approved?Run file codeWork with the chosen fileReturn earlyCanceled or closedreturns valueyesno
After the user closes the JFileChooser, which branch does the program take based on the returned value, and which file code is skipped?
Worked example

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.

  1. 1
    Outcome 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.

  2. 2
    Outcome 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.

  3. 3
    Compare 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.

Result

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?

java
Notes on the code
  • 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.
Get selected filegetSelectedFile()File exists?selectedFile.exists()Ask to replaceJOptionPane.showConfirmDialogNo confirmationneededyesno
In what order do the existence check and the overwrite confirmation happen, and what does the source show after that?

Mistakes Beginners Make with Dialogs

  • Common mistake

    Running file code right after showing the dialog without checking the result

    What it looks like

    Calling a read or write immediately after showOpenDialog or showSaveDialog returns.

    Why it fails

    If 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 instead

    Check 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 like

    Calling showOpenDialog(this) in a method that saves data.

    Why it fails

    The source uses showSaveDialog(this) for writing and showOpenDialog(this) for reading. The method call is what sets the dialog's purpose.

    Do this instead

    Use 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 fails

    writeFile() calls exists() and, when a file is present, asks the user to confirm replacement with JOptionPane.showConfirmDialog.

    Do this instead

    Expect 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 like

    Expecting the user to see a highlighted file the moment the reading dialog opens.

    Why it fails

    readFile() calls setSelectedFile(null), so no file is initially selected.

    Do this instead

    Set 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

MEDIUM

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

  • JFileChooser creates 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 uses showSaveDialog(this) with a default name of output.txt and 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 whether JOptionPane.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.