DevFaqDialogsApiIntro

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

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: Image:OkDialog.png

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.

Image:YesNoDialog.png

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:

Image:InputDialog.png

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):

Image:CustomPanelDialog.png

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...
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo