O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using JOptionPane

There are basically two ways to use JOptionPane . The simplest, demonstrated by the example at the beginning of this section, is to invoke one of the many static methods of the class. These methods all result in a JDialog or JInternalFrame being displayed immediately for the user. The methods return when the user clicks one of the buttons in the dialog.

The other way to use JOptionPane is to instantiate it using one of the many constructors and then call createDialog( ) or createInternalFrame( ). These methods give you access to the JDialog or JInternalFrame and allow you to control when and where they are displayed. In most cases, the static methods will do everything you need. As with JDialog constructors, the static methods can (since 1.4) potentially throw a HeadlessException if the graphics environment is operating in a “headless” mode, meaning that there is no display, keyboard, or mouse.

It’s worth noting that JOptionPane extends JComponent. When you instantiate JOptionPane, you actually have a perfectly usable component, laid out with the structure we described earlier. If you wanted to, you could display the component directly, but it typically makes sense to use it only in a dialog or internal frame.

Tip

All of the methods in JOptionPane that result in the creation of a JDialog create modal dialogs, but the methods that display JInternalFrames do not enforce modality. When the internal frame dialog is displayed, the other windows in your application can still ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required