Swing Dialogs: JOptionPane, Custom Dialogs and JFileChooser
Asking the user for input in Swing: ready-made JOptionPane message, confirm, option and input dialogs; custom JDialog classes with modality types, default buttons and data exchange; and file selection with JFileChooser, filters, views and accessories.
kvi5hnuCode Sprout team member14 min readOn this page
Besides its main window, an application regularly needs short-lived windows: to report an error, ask for confirmation, collect a user name and password, or let the user pick a file. These are dialogs. A modal dialog blocks interaction with the rest of the application until it is closed; use it when the program cannot continue without the answer, as in "Open file". A modeless dialog can stay open while the user keeps working in other windows, like a find-and-replace box or a floating palette.
This article starts with the ready-made dialogs of JOptionPane, then shows how to build your own with JDialog and pass data in and out, and ends with the file chooser.
Option panes
For a single piece of information, JOptionPane has static methods that build, show and dispose of a complete dialog:
| Method | Shows | Returns |
|---|---|---|
showMessageDialog | a message and an OK button | nothing |
showConfirmDialog | a message and Yes/No/Cancel or OK/Cancel buttons | an int option constant |
showOptionDialog | a message and buttons of your choice | the index of the chosen option |
showInputDialog | a message and a text field or combo box | the entered or selected value, or null |
Each dialog has an icon, a message, one or more buttons and, for input dialogs, an input component. The icon follows from the message type: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE (no icon). Every method also has an overload that takes your own icon. The look and feel determines the exact layout and icons.
The message is usually a string; newlines in it produce several lines, and HTML works as in labels. It can also be an icon (shown), a component (shown as is, so you can put any panel in an option pane), an array of objects (all shown, stacked vertically, which is how you add a "Don't ask again" check box below a question), or any other object (its toString is shown).
The buttons depend on the method. Message dialogs get OK and input dialogs OK and Cancel. Confirm dialogs take an option type: DEFAULT_OPTION (OK only), YES_NO_OPTION, YES_NO_CANCEL_OPTION or OK_CANCEL_OPTION. Option dialogs take an array of options, each a string or icon (shown on a button) or a component (shown as is), plus the initially selected one.
The return values: a confirm dialog returns YES_OPTION, NO_OPTION, CANCEL_OPTION or OK_OPTION, or CLOSED_OPTION (-1) if the user closed the window. Note that OK_OPTION and YES_OPTION are both 0. An option dialog returns the index of the chosen option or CLOSED_OPTION. An input dialog returns the string (or selected object), or null for Cancel.
So, to use an option pane: choose the kind of dialog, the message type, the message, and the option type or options, then find the matching method:
int selection = JOptionPane.showConfirmDialog(parent,
"Discard unsaved changes?", "Close document",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (selection == JOptionPane.OK_OPTION) { ... }
Object[] options = {"Overwrite", "Keep both", "Skip"};
int choice = JOptionPane.showOptionDialog(parent, "report.txt already exists.", "Copy",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
String name = JOptionPane.showInputDialog(parent, "Your name:", "guest");
Object planet = JOptionPane.showInputDialog(parent, "Planet:", "Choose",
JOptionPane.QUESTION_MESSAGE, null, new String[] {"Mercury", "Venus", "Earth"}, "Earth");
Always handle the "closed" case: with CLOSED_OPTION or null, the user backed out. Use clear verbs on buttons where possible ("Overwrite", "Keep both") instead of a vague Yes/No; that is what option dialogs are for. The parent argument may be null, but passing a component centers the dialog over its window and makes it the dialog's owner, which matters on multi-monitor setups.
There are also showInternal...Dialog variants that draw the dialog inside a JDesktopPane (an application with internal frames). And if you need more control, construct a JOptionPane object yourself and call its createDialog(parent, title) method, which returns a JDialog you can adjust (for example, make it modeless or resizable) before showing it. The demo constructs option panes this way, without showing them, to inspect the buttons they create and the values they produce.
Creating your own dialogs
When an option pane is not enough, write a dialog class. The process mirrors creating a frame:
- Extend
JDialogand call a superclass constructor with the owner window, a title, and the modality. - Add the components.
- Add event handlers.
- Call
pack()(or set a size).
public class AboutDialog extends JDialog {
public AboutDialog(JFrame owner) {
super(owner, "About", Dialog.ModalityType.APPLICATION_MODAL);
add(new JLabel("<html><h2>MyEditor 2.1</h2>Written with Swing</html>"), BorderLayout.CENTER);
var ok = new JButton("OK");
ok.addActionListener(_ -> setVisible(false));
var panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH);
pack();
}
}
Show it with dialog.setVisible(true). A dialog can be created once and shown repeatedly; hiding it (with setVisible(false), which is also the default action of the window's close box) keeps it ready for next time. Call dispose() when you no longer need it.
The owner determines where the dialog appears and links its lifetime to the owner's: the dialog stays in front of its owner and is minimized and closed with it. Passing null makes a hidden shared frame the owner, which works but loses these benefits. The modality has four levels, given by Dialog.ModalityType:
MODELESS: blocks nothing;DOCUMENT_MODAL: blocks the windows of the same top-level window hierarchy (the "document");APPLICATION_MODAL: blocks all windows of the application, except the dialog's own children;TOOLKIT_MODAL: blocks all windows in the same toolkit, which matters only when several applications share a JVM.
The older constructors with a boolean modal parameter map true to APPLICATION_MODAL, as the demo confirms.
Data exchange
Most dialogs exist to collect data. The pattern for a modal dialog is shown in the diagram:

- Before showing, put default values into the dialog (for example,
setUser(...)). - Call
setVisible(true). For a modal dialog, this call blocks until the dialog is hidden. The event dispatch thread keeps processing events inside the call, so the dialog works normally. - The OK button's listener records that the user accepted, then calls
setVisible(false). Cancel and the close box only hide the dialog. setVisible(true)returns; check the flag and read the values.
Expose the result through methods (getUser(), getPassword()) or, more neatly, return a record from a showDialog method, with null or an empty Optional for Cancel.
Two refinements are common. First, the owner frame may not be known when the dialog object is built, or the same dialog may be used from several windows. You can then build the content as a JPanel and create the JDialog around it on demand in a showDialog(Component parent, String title) method, finding the owner with SwingUtilities.getWindowAncestor(parent) and creating a new dialog only when the owner changes. The demo's LoginPanel does this, and it can be tested without any window: setting fields and clicking its buttons with doClick exercises all the logic.
Second, make the dialog keyboard-friendly. A default button is pressed when the user presses Enter: dialog.getRootPane().setDefaultButton(okButton). If the content is a panel, set it after putting the panel into the dialog, because a panel on its own has no root pane (the demo prints null). Users also expect Escape to cancel; register a keyboard action on the root pane, as the listing below does.
Modeless dialogs cannot use this pattern, since setVisible(true) returns immediately. Their buttons must instead call back into the application, for example through a listener interface or a Consumer passed to the dialog, at the moment the user clicks Apply or OK.
File dialogs
Choosing files is so common, and a good file browser so much work, that Swing provides one: JFileChooser. It is not a JDialog subclass; it is a component that creates a modal dialog when you call one of its show methods:
- Create a
JFileChooser, without a parent. Reuse it: construction can be slow (on Windows with many network drives, noticeably so), and a reused chooser remembers the last directory. - Set the starting directory:
chooser.setCurrentDirectory(new File(System.getProperty("user.home"))). - Optionally suggest a file:
setSelectedFile(new File("report.txt")), typical for Save dialogs. - Optionally allow selecting several files:
setMultiSelectionEnabled(true). - Optionally set file filters (below).
- Choose what can be selected:
setFileSelectionModewithFILES_ONLY(default),DIRECTORIES_ONLYorFILES_AND_DIRECTORIES. - Show the dialog:
showOpenDialog(parent),showSaveDialog(parent), orshowDialog(parent, "Import")with your own text for the approve button. The call returnsAPPROVE_OPTION,CANCEL_OPTION(also for closing the window) orERROR_OPTION. - Get the result with
getSelectedFile()orgetSelectedFiles(), and convert withtoPath()if you work withjava.nio.file.
if (chooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
Path target = chooser.getSelectedFile().toPath();
if (Files.exists(target) && JOptionPane.showConfirmDialog(frame, "Replace " + target.getFileName() + "?",
"Save", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return;
Files.writeString(target, text);
}
The save dialog does not ask before overwriting an existing file; that confirmation is your job, as the snippet shows. It also does not add an extension: if the user types "report", you get exactly that name.
File filters
A filter restricts the displayed files. FileNameExtensionFilter covers the usual case; it compares extensions without regard to case and always accepts directories, so the user can still navigate:
chooser.setFileFilter(new FileNameExtensionFilter("Images", "png", "jpg", "jpeg", "gif"));
For other criteria, extend the abstract class javax.swing.filechooser.FileFilter and implement accept(File) and getDescription(). Watch out for the unrelated interface java.io.FileFilter, used by File.listFiles; if you import both packages with wildcards, the name is ambiguous, so import javax.swing.filechooser.FileFilter explicitly.
setFileFilter installs a filter and selects it; addChoosableFileFilter adds more to the filter combo box. The "All Files" filter is included unless you call setAcceptAllFileFilterUsed(false), but keep it in general: users sometimes have files with unusual extensions. When you reuse one chooser for different purposes, clear old filters with resetChoosableFileFilters().
File views and accessories
A FileView customizes how files are shown: icon, name, description, type description, and whether a directory can be opened (isTraversable, which returns a Boolean so that null means "use the default"). Every method may return null to fall back to the look and feel's view, so you only handle the files you care about. Install it with setFileView.
An accessory is any component shown beside the file list, typically a preview. Install it with setAccessory. To update it, listen for the chooser's property changes:
chooser.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY, event -> {
if (event.getNewValue() instanceof File f && f.isFile()) showPreview(f);
else clearPreview();
});
Handle null: the demo shows that switching to multi-selection mode clears the selection, firing an event whose new value is null.
On macOS, users may prefer the native file dialog. The AWT class java.awt.FileDialog uses it, with fewer options (no accessories, and filters through a FilenameFilter that some platforms ignore). Setting the system property apple.awt.fileDialogForDirectories to "true" lets it choose directories on macOS.
A program with dialogs
The following program shows a message dialog for About, a custom modal login dialog with a default button and Escape to cancel, a reused file chooser with an image filter and preview accessory, and a confirmation dialog when the user closes the window (the frame uses DO_NOTHING_ON_CLOSE and decides in a window listener).
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public final class DialogsFrame extends JFrame {
private static final long serialVersionUID = 1L;
private final JTextArea log = new JTextArea(12, 40);
private final JFileChooser chooser = new JFileChooser(); // reused: construction can be slow
private LoginDialog loginDialog; // created on first use
public DialogsFrame() {
super("Dialogs");
log.setEditable(false);
add(new JScrollPane(log));
var file = new JMenu("File");
file.add("Connect...").addActionListener(_ -> connect());
file.add("Open image...").addActionListener(_ -> openImage());
file.addSeparator();
file.add("Exit").addActionListener(_ -> confirmExit());
var help = new JMenu("Help");
help.add("About").addActionListener(_ -> JOptionPane.showMessageDialog(this,
"<html><h2>Dialogs</h2>A tour of Swing dialogs.</html>", "About",
JOptionPane.INFORMATION_MESSAGE));
var bar = new JMenuBar();
bar.add(file);
bar.add(help);
setJMenuBar(bar);
chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
chooser.setFileFilter(new FileNameExtensionFilter("Images", "png", "jpg", "jpeg", "gif"));
var preview = new JLabel("", SwingConstants.CENTER);
preview.setPreferredSize(new Dimension(160, 160));
preview.setBorder(BorderFactory.createEtchedBorder());
chooser.setAccessory(preview);
chooser.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY, e -> {
if (e.getNewValue() instanceof File f && f.isFile()) {
Image image = new ImageIcon(f.getPath()).getImage()
.getScaledInstance(150, -1, Image.SCALE_SMOOTH);
preview.setIcon(new ImageIcon(image));
} else {
preview.setIcon(null);
}
});
// ask before closing the window
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) { confirmExit(); }
});
pack();
setLocationByPlatform(true);
}
private void connect() {
if (loginDialog == null) loginDialog = new LoginDialog(this);
loginDialog.setUser("yourname");
if (loginDialog.showDialog()) { // blocks until the dialog is closed
char[] password = loginDialog.getPassword();
log.append("Connecting as " + loginDialog.getUser()
+ " (password: " + password.length + " characters)\n");
Arrays.fill(password, '\0');
} else {
log.append("Connection canceled\n");
}
}
private void openImage() {
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
log.append("Selected " + chooser.getSelectedFile() + "\n");
}
private void confirmExit() {
int answer = JOptionPane.showConfirmDialog(this, "Really quit?", "Exit",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer == JOptionPane.OK_OPTION) dispose();
}
/** A modal dialog with a user name and password; the caller reads the fields afterwards. */
static final class LoginDialog extends JDialog {
private static final long serialVersionUID = 1L;
private final JTextField user = new JTextField(16);
private final JPasswordField password = new JPasswordField(16);
private boolean accepted;
LoginDialog(Frame owner) {
super(owner, "Connect", ModalityType.APPLICATION_MODAL);
var fields = new JPanel(new GridLayout(2, 2, 4, 4));
fields.add(new JLabel("User name:"));
fields.add(user);
fields.add(new JLabel("Password:"));
fields.add(password);
fields.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
add(fields, BorderLayout.CENTER);
var ok = new JButton("OK");
ok.addActionListener(_ -> { accepted = true; setVisible(false); });
var cancel = new JButton("Cancel");
cancel.addActionListener(_ -> setVisible(false));
var buttons = new JPanel();
buttons.add(ok);
buttons.add(cancel);
add(buttons, BorderLayout.SOUTH);
getRootPane().setDefaultButton(ok);
// Escape closes the dialog like Cancel
getRootPane().registerKeyboardAction(_ -> setVisible(false),
KeyStroke.getKeyStroke("ESCAPE"), JComponent.WHEN_IN_FOCUSED_WINDOW);
pack();
}
void setUser(String name) {
user.setText(name);
password.setText("");
}
String getUser() { return user.getText().strip(); }
char[] getPassword() { return password.getPassword(); }
boolean showDialog() {
accepted = false;
setLocationRelativeTo(getOwner());
setVisible(true); // modal: returns after setVisible(false) or closing
return accepted;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new DialogsFrame().setVisible(true));
}
}
The program
The demo cannot open windows, so it constructs the components that the dialogs contain and drives them directly: option panes (clicking their buttons), the login panel (filling fields and clicking OK and Cancel) and a file chooser over a temporary directory. It sets the default locale to US English first, because button texts such as "Yes" and "Cancel" come from localized resources.
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileView;
public class Solution {
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
Locale.setDefault(Locale.US); // button texts come from localized resources
Path dir = Files.createTempDirectory("chooser");
try {
for (String name : List.of("photo.JPG", "notes.txt", "scan.jpeg", "logo.png"))
Files.writeString(dir.resolve(name), name);
Files.createDirectory(dir.resolve("albums"));
EventQueue.invokeAndWait(() -> run(dir));
} finally {
try (var files = Files.walk(dir)) {
files.sorted((a, b) -> b.compareTo(a)).forEach(p -> p.toFile().delete());
}
}
}
static void run(Path dir) {
optionPanes();
dataExchange();
fileChoosers(dir.toFile());
modality();
}
static List<JButton> buttons(Container c) {
List<JButton> result = new ArrayList<>();
for (Component child : c.getComponents()) {
if (child instanceof JButton b) result.add(b);
else if (child instanceof Container k) result.addAll(buttons(k));
}
return result;
}
static void optionPanes() {
System.out.println("== JOptionPane: what the show... methods build ==");
System.out.println("constants: YES/OK=" + JOptionPane.YES_OPTION + ", NO=" + JOptionPane.NO_OPTION
+ ", CANCEL=" + JOptionPane.CANCEL_OPTION + ", CLOSED=" + JOptionPane.CLOSED_OPTION);
int[][] types = {
{JOptionPane.DEFAULT_OPTION}, {JOptionPane.YES_NO_OPTION},
{JOptionPane.YES_NO_CANCEL_OPTION}, {JOptionPane.OK_CANCEL_OPTION}};
String[] names = {"DEFAULT_OPTION", "YES_NO_OPTION", "YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION"};
for (int i = 0; i < types.length; i++) {
var pane = new JOptionPane("Message", JOptionPane.QUESTION_MESSAGE, types[i][0]);
System.out.printf(" %-21s buttons %s%n", names[i],
buttons(pane).stream().map(AbstractButton::getText).toList());
}
var confirm = new JOptionPane("Save changes before closing?",
JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
confirm.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY,
e -> System.out.println(" value property changed to " + e.getNewValue()));
buttons(confirm).get(1).doClick(0); // the user clicks "No"
System.out.println("confirm dialog would return " + confirm.getValue()
+ " (NO_OPTION = " + JOptionPane.NO_OPTION + ")");
Object[] options = {"Overwrite", "Keep both", "Skip"};
var choose = new JOptionPane("report.txt already exists.", JOptionPane.QUESTION_MESSAGE,
JOptionPane.DEFAULT_OPTION, null, options, options[1]);
System.out.println("custom options: " + buttons(choose).stream().map(AbstractButton::getText).toList()
+ ", initial value " + choose.getInitialValue());
buttons(choose).get(2).doClick(0);
int index = Arrays.asList(options).indexOf(choose.getValue());
System.out.println("option dialog would return index " + index + " for \"" + choose.getValue() + "\"");
var input = new JOptionPane("Your name:", JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
input.setWantsInput(true);
input.setInitialSelectionValue("guest");
input.selectInitialValue();
JTextField field = find(input, JTextField.class);
System.out.println("input pane has a text field: " + (field != null)
+ ", prefilled \"" + field.getText() + "\"");
field.setText("Ada");
field.postActionEvent(); // Enter in the field commits the input
System.out.println("after Enter: input value \"" + input.getInputValue() + "\", value " + input.getValue());
buttons(input).get(0).doClick(0); // OK
System.out.println("after OK: value " + input.getValue() + ", so showInputDialog would return \""
+ input.getInputValue() + "\"");
var pick = new JOptionPane("Planet:", JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
pick.setWantsInput(true);
pick.setSelectionValues(new Object[] {"Mercury", "Venus", "Earth"});
pick.setInitialSelectionValue("Earth");
System.out.println("with selection values the input is a "
+ find(pick, JComboBox.class).getClass().getSimpleName());
var stacked = new JOptionPane(new Object[] {"Line one\nLine two", new JCheckBox("Do not ask again")});
System.out.println("message array -> check box included: " + (find(stacked, JCheckBox.class) != null)
+ ", message lines shown as " + count(stacked, JLabel.class) + " labels");
for (String key : List.of("errorIcon", "informationIcon", "warningIcon", "questionIcon"))
System.out.println(" OptionPane." + key + " present: " + (UIManager.getIcon("OptionPane." + key) != null));
}
static <T> T find(Container c, Class<T> type) {
for (Component child : c.getComponents()) {
if (type.isInstance(child)) return type.cast(child);
if (child instanceof Container k) {
T t = find(k, type);
if (t != null) return t;
}
}
return null;
}
static int count(Container c, Class<?> type) {
int n = 0;
for (Component child : c.getComponents()) {
if (type.isInstance(child)) n++;
if (child instanceof Container k) n += count(k, type);
}
return n;
}
record Login(String user, char[] password) { }
/** The panel of a login dialog; the dialog itself is created when shown. */
static class LoginPanel extends JPanel {
private static final long serialVersionUID = 1L;
final JTextField user = new JTextField(12);
final JPasswordField password = new JPasswordField(12);
final JButton ok = new JButton("OK");
final JButton cancel = new JButton("Cancel");
private boolean accepted;
private JDialog dialog;
LoginPanel() {
super(new BorderLayout());
var fields = new JPanel(new GridLayout(2, 2));
fields.add(new JLabel("User name:"));
fields.add(user);
fields.add(new JLabel("Password:"));
fields.add(password);
add(fields, BorderLayout.CENTER);
var buttons = new JPanel();
buttons.add(ok);
buttons.add(cancel);
add(buttons, BorderLayout.SOUTH);
ok.addActionListener(_ -> close(true));
cancel.addActionListener(_ -> close(false));
}
void setDefaults(Login l) { user.setText(l.user()); password.setText(""); }
Login getLogin() { return new Login(user.getText().strip(), password.getPassword()); }
private void close(boolean accept) {
accepted = accept;
if (dialog != null) dialog.setVisible(false); // ends the blocking setVisible(true)
}
/** Shows the panel in a modal dialog owned by the parent's window; blocks until closed. */
boolean showDialog(Component parent, String title) {
accepted = false;
Window owner = parent instanceof Window w ? w : SwingUtilities.getWindowAncestor(parent);
if (dialog == null || dialog.getOwner() != owner) {
dialog = new JDialog(owner, title, Dialog.ModalityType.APPLICATION_MODAL);
dialog.add(this);
dialog.getRootPane().setDefaultButton(ok);
dialog.pack();
}
dialog.setTitle(title);
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
return accepted;
}
boolean wasAccepted() { return accepted; }
}
static void dataExchange() {
System.out.println();
System.out.println("== Data exchange with a dialog panel (driven without a window) ==");
var panel = new LoginPanel();
panel.setDefaults(new Login("yourname", null));
System.out.println("defaults set: user \"" + panel.user.getText() + "\"");
panel.user.setText(" ada ");
panel.password.setText("analytical");
panel.ok.doClick(0);
Login l = panel.getLogin();
System.out.println("accepted " + panel.wasAccepted() + ": user \"" + l.user() + "\", password of "
+ l.password().length + " characters");
Arrays.fill(l.password(), '\0');
panel.cancel.doClick(0);
System.out.println("after Cancel: accepted " + panel.wasAccepted());
System.out.println("panel's root pane before it is in a dialog: " + panel.getRootPane());
}
static void fileChoosers(File dir) {
System.out.println();
System.out.println("== JFileChooser configured without being shown ==");
var chooser = new JFileChooser();
chooser.setCurrentDirectory(dir);
var images = new FileNameExtensionFilter("Image files", "jpg", "jpeg", "png");
chooser.setFileFilter(images);
System.out.println("choosable filters: " + Arrays.stream(chooser.getChoosableFileFilters())
.map(FileFilter::getDescription).toList());
String[] names = dir.list();
Arrays.sort(names);
for (String name : names) {
File f = new File(dir, name);
System.out.printf(" %-10s accepted %-5s (%s)%n", name, images.accept(f),
f.isDirectory() ? "directory" : "file");
}
chooser.setAcceptAllFileFilterUsed(false);
System.out.println("without \"All files\": " + chooser.getChoosableFileFilters().length + " filter");
chooser.resetChoosableFileFilters();
System.out.println("after reset: " + Arrays.stream(chooser.getChoosableFileFilters())
.map(FileFilter::getDescription).toList());
chooser.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY,
(PropertyChangeEvent e) -> System.out.println(" selected file changed to "
+ (e.getNewValue() instanceof File f ? f.getName() : "none")));
chooser.setSelectedFile(new File(dir, "photo.JPG"));
chooser.setSelectedFile(new File(dir, "logo.png"));
System.out.println("selected: " + chooser.getSelectedFile().getName());
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setMultiSelectionEnabled(true);
System.out.println("directories only: " + (chooser.getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY)
+ ", multi-selection: " + chooser.isMultiSelectionEnabled());
System.out.println("return codes: APPROVE=" + JFileChooser.APPROVE_OPTION + ", CANCEL="
+ JFileChooser.CANCEL_OPTION + ", ERROR=" + JFileChooser.ERROR_OPTION);
FileView view = new FileView() {
@Override public String getTypeDescription(File f) {
return images.accept(f) && !f.isDirectory() ? "Picture" : null; // null: use the default
}
};
chooser.setFileView(view);
System.out.println("file view: logo.png -> " + view.getTypeDescription(new File(dir, "logo.png"))
+ ", notes.txt -> " + view.getTypeDescription(new File(dir, "notes.txt")));
var preview = new JLabel("preview");
chooser.setAccessory(preview);
System.out.println("accessory installed: " + (chooser.getAccessory() == preview));
}
static void modality() {
System.out.println();
System.out.println("== Modality types ==");
for (Dialog.ModalityType t : Dialog.ModalityType.values())
System.out.println(" " + t);
System.out.println("JDialog(owner, title, true) means " + Dialog.DEFAULT_MODALITY_TYPE);
}
}
== JOptionPane: what the show... methods build ==
constants: YES/OK=0, NO=1, CANCEL=2, CLOSED=-1
DEFAULT_OPTION buttons [OK]
YES_NO_OPTION buttons [Yes, No]
YES_NO_CANCEL_OPTION buttons [Yes, No, Cancel]
OK_CANCEL_OPTION buttons [OK, Cancel]
value property changed to 1
confirm dialog would return 1 (NO_OPTION = 1)
custom options: [Overwrite, Keep both, Skip], initial value Keep both
option dialog would return index 2 for "Skip"
input pane has a text field: true, prefilled "guest"
after Enter: input value "Ada", value uninitializedValue
after OK: value 0, so showInputDialog would return "Ada"
with selection values the input is a JComboBox
message array -> check box included: true, message lines shown as 2 labels
OptionPane.errorIcon present: true
OptionPane.informationIcon present: true
OptionPane.warningIcon present: true
OptionPane.questionIcon present: true
== Data exchange with a dialog panel (driven without a window) ==
defaults set: user "yourname"
accepted true: user "ada", password of 10 characters
after Cancel: accepted false
panel's root pane before it is in a dialog: null
== JFileChooser configured without being shown ==
choosable filters: [All Files, Image files]
albums accepted true (directory)
logo.png accepted true (file)
notes.txt accepted false (file)
photo.JPG accepted true (file)
scan.jpeg accepted true (file)
without "All files": 1 filter
after reset: []
selected file changed to photo.JPG
selected file changed to logo.png
selected: logo.png
selected file changed to none
directories only: true, multi-selection: true
return codes: APPROVE=0, CANCEL=1, ERROR=-1
file view: logo.png -> Picture, notes.txt -> null
accessory installed: true
== Modality types ==
MODELESS
DOCUMENT_MODAL
APPLICATION_MODAL
TOOLKIT_MODAL
JDialog(owner, title, true) means APPLICATION_MODAL
Points to notice:
- Clicking the second button of a Yes/No/Cancel pane set its value to 1, which is
NO_OPTION;showConfirmDialogreturns exactly that value. - For custom options, the value is the option object itself;
showOptionDialogconverts it to its index. - Pressing Enter in an input pane's text field stored the input value but did not set the pane's value; clicking OK set the value to 0 (
OK_OPTION) and copied the field's text into the input value. After Cancel, the input value stays uninitialized, andshowInputDialogthen returnsnull. FileNameExtensionFilteracceptedphoto.JPG(case-insensitive) and the directoryalbums.- Enabling multi-selection fired a selected-file change with a
nullnew value.
Common questions
How do I show a dialog from a background thread?
Don't call Swing from the background thread. Use SwingUtilities.invokeAndWait if the thread needs the answer, or invokeLater for a message. Better, report back to the EDT (for example from SwingWorker.done()) and show the dialog there.
Why does code after setVisible(true) not run until the dialog closes?
Because the dialog is modal: setVisible(true) blocks until it is hidden, while still processing events. That's the intended behavior and how you read results. Use a modeless dialog if the code should continue.
How do I make a dialog close with Escape?
Bind KeyStroke.getKeyStroke("ESCAPE") in dialog.getRootPane()'s WHEN_IN_FOCUSED_WINDOW input map to an action that calls setVisible(false) or dispose().
How do I add the extension when the user types "report" in a save dialog?
Check the name after APPROVE_OPTION: if it lacks the extension of the selected filter, append it (new File(file.getPath() + ".png")). Then ask before overwriting if that file exists.
JFileChooser or FileDialog?
JFileChooser for consistent behavior, filters, accessories and previews. java.awt.FileDialog for the native dialog, which macOS users in particular prefer, with fewer customization options.
API reference
| Class / method | Purpose |
|---|---|
JOptionPane.showMessageDialog, showConfirmDialog, showOptionDialog, showInputDialog | Ready-made modal dialogs. |
ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE | Message types (icons). |
DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION | Option types. |
YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, CLOSED_OPTION | Return values. |
new JOptionPane(...), createDialog(parent, title), getValue, getInputValue, setWantsInput | Option pane as an object. |
JDialog(owner, title, modalityType), Dialog.ModalityType | Custom dialogs and modality. |
Window.setVisible, dispose, pack, setLocationRelativeTo | Showing and closing. |
SwingUtilities.getWindowAncestor, getAncestorOfClass | Finding the owner window. |
JRootPane.setDefaultButton, JButton.isDefaultButton, JComponent.getRootPane | Default button. |
JFileChooser(), setCurrentDirectory, setSelectedFile, setMultiSelectionEnabled, setFileSelectionMode | File chooser setup. |
JFileChooser.showOpenDialog, showSaveDialog, showDialog, getSelectedFile, getSelectedFiles; APPROVE_OPTION, CANCEL_OPTION, ERROR_OPTION | Showing and results. |
setFileFilter, addChoosableFileFilter, setAcceptAllFileFilterUsed, resetChoosableFileFilters, FileNameExtensionFilter | Filters. |
setFileView, FileView.getIcon/getName/getDescription/getTypeDescription/isTraversable, setAccessory, SELECTED_FILE_CHANGED_PROPERTY | Views and accessories. |
Summary
JOptionPaneprovides message, confirm, option and input dialogs in one call. Choose message type, message, option type or options, and handle the closed/nullresult.- Custom dialogs extend
JDialog, with an owner and aModalityType. They can be created once and shown repeatedly. - For a modal dialog,
setVisible(true)blocks until the dialog is hidden; set defaults before and read results (and an accepted flag) after. Add a default button and Escape handling. JFileChooserprovides open and save dialogs. Reuse it, check the return code, confirm overwrites yourself, and narrow the files with filters; customize with aFileViewand an accessory.
Practice Questions
1. showConfirmDialog returned -1. What happened, and why is it a mistake to treat every value other than YES_OPTION as "No"?
-1 is CLOSED_OPTION: the user closed the dialog window without clicking a button. Treating it as "No" may perform an action the user did not choose, for example discarding changes when the user just wanted to back out. Usually a closed dialog should be treated like Cancel.
2. In a modal dialog, how does the calling code find out whether the user clicked OK or Cancel?
The OK button's listener sets a field (such as accepted = true) before hiding the dialog; Cancel and the close box hide it without setting the field. Because setVisible(true) blocks until the dialog is hidden, the code after that call can simply check the field and then read the entered values.
3. A dialog's content is built as a JPanel. The constructor of the panel calls getRootPane().setDefaultButton(okButton) and fails with a NullPointerException. Why?
A panel that has not yet been added to a window has no root pane, so getRootPane() returns null. Set the default button after the panel has been placed in the JDialog, using the dialog's root pane.
4. A user types "notes" into a JFileChooser save dialog that has a filter for .txt files, and the program writes to the file "notes". What went wrong, and what else should the program check before writing?
The file chooser returns exactly what the user typed; it does not add the extension of the selected filter. The program should add ".txt" if the name has no extension. It should also check whether the file exists and ask before overwriting it, since the save dialog does not do that either.
5. When is a modeless dialog more appropriate than a modal one, and how does it pass data back?
When the user should be able to keep working in the main window while the dialog is open, for example a find-and-replace dialog, a color palette or a properties inspector. Since setVisible(true) returns immediately for a modeless dialog, it cannot return data at the end of a blocking call; instead its buttons notify the application through a callback (a listener or a functional interface supplied by the caller) whenever the user applies a change.
Previous: GridBagLayout and Custom Layout Managers in Swing
Next: Swing Tables: JTable, Table Models, Sorting and Filtering
Related reading
- GridBagLayout and Custom Layout Managers in Swing
- Swing Menus, Toolbars and Tooltips: Mnemonics, Accelerators and Popup Menus
- Swing Choice Components: Check Boxes, Radio Buttons, Borders, Combo Boxes and Sliders
- Swing Text Components: Text Fields, Labels, Password Fields and Text Areas
- Swing Layout Managers and MVC: FlowLayout, BorderLayout and GridLayout

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.