Java Reference
In-Depth Information
The dialog pops up when you select the About item in the Help menu. Until you select the OK button in
the About Sketcher dialog, you can't interact with the application window at all since we created this as
a modal dialog. By changing the last argument in the call to the superclass constructor in the
AboutDialog constructor, you can make it non-modal and see how that works. This kind of dialog is
usually modal though.
If you resize the application window before you display the About dialog, you'll see that its position of
the dialog relative to the application window is adjusted accordingly.
How It Works
This is stuff that should be very familiar by now. We create a JMenu object for the Help item on the
menu bar, and add a shortcut for it by calling its setMnemonic() member. We create a JMenuItem
object which is the About menu item and call its addActionListener() method to make the
SketchFrame object the listener for the item. After adding the menu item to the Help menu, we add
the helpMenu object to the menubar object.
We create an AboutDialog object in the actionPerformed() method for the SketchFrame
object, as this will be called when the About menu item is clicked. Before we display the dialog, we
verify that the source of the event is the menu item, aboutItem . This is not important now, but we will
add other menu items later, and we will want to handle their events using the same
actionPerformed() method. The dialog object is self-contained and disposes of itself when the OK
button is clicked. The dialog that we want to display here will always display the same message, so
there's no real point in creating and destroying it each time we want to display it. You could arrange for
the dialog box object to be created once, and the reference stored as a member of the SketchFrame
class. Then you make it visible in the actionPerformed() method for the menu item and make it
invisible in the actionPerformed() method responding to the dialog OK button event.
This is all very well, but it was a lot of work just to get a dialog with a message displayed. Deriving a
class from JDialog gives you complete flexibility as to how the dialog works, but we didn't really need
it in this case. Didn't we say there was an easier way?
Instant Dialogs
The JOptionPane class in the javax.swing package defines a number of static methods that will
create and display standard modal dialogs for you. The simplest dialog you can create this way is a
message dialog rather like our About message dialog. The following methods produce message dialogs:
Search WWH ::




Custom Search