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 JInternalFrame
s do not enforce modality. When the internal frame dialog is displayed, the other windows in your application can still ...
Get Java Swing, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.