What is the Dialogs API and How Do I Use It?

Apache NetBeans Wiki Index

Note: These pages are being reviewed.

The Dialogs API provides support for dialogs and wizards.

Whenever you’d use JDialog or JOptionPane in Swing, using the Dialogs API provides some alternatives. These are easier to use as they automatically take care of centering and other display details, but also allow you to later plug in a different implementation of how they’re actually "displayed." Instead of showing them on screen, for example, you could override the default DialogDisplayer class to specify your own that logged them to a printer or read them aloud using speech synthesis.

I’ll illustrate three of the most common use cases. The first is when you want to simply show a dialog box with some text: OkDialog

String msg = "There is something you should know...";
NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE);
DialogDisplayer.getDefault().notify(nd);

For a question to users, you’ll use a similar mechanism.

YesNoDialog

The msg argument is optional here:

String msg = "Something is going to happen. Do you want to continue?";
NotifyDescriptor nd = new NotifyDescriptor.Confirmation(msg, NotifyDescriptor.YES_NO_OPTION);
Object result = DialogDisplayer.getDefault().notify(nd);
if (NotifyDescriptor.OK_OPTION == result) {
    // do it
} else {
    // don't do it
}

And to request simple user input:

InputDialog

String txt = "Name: ";
String title = "State your name";

NotifyDescriptor.InputLine input = new NotifyDescriptor.InputLine(txt, title);
input.setInputText("John Doe"); // specify a default name
Object result = DialogDisplayer.getDefault().notify(input);
if (result != NotifyDescriptor.OK_OPTION) {
    return;
}

String userInput = input.getInputText();

And finally, the DialogDescriptor subclass, handles complex cases (there are many variants here; see Dialog Descriptor’s Javadoc for details):

CustomPanelDialog

JPanel form = new MyComplexForm();
String msg = "Something bad happened...";
DialogDescriptor dd = new DialogDescriptor(form, msg);
Object result = DialogDisplayer.getDefault().notify(dd);
if (result != NotifyDescriptor.OK_OPTION) {
    return;
}

// you can now examine the form's state...