Java Reference
In-Depth Information
By default the
AboutDialog
window will be positioned relative to the top-left corner of the screen. To
position the dialog appropriately, we set the coordinates of the top-left corner of the dialog as one
quarter of the distance across the width of the application window, and one quarter of the distance down
from the top-left corner of the application window.
You add the components you want to display in a dialog to the content pane for the
JDialog
object.
The content pane has a
BorderLayout
manager by default, just like the content pane for the
application window, and this is quite convenient for our dialog layout. The dialog contains two
JPanel
objects that are created in the constructor, one to hold a
JLabel
object for the message that is passed to
the constructor, and the other to hold the
OK
button that will close the dialog. The
messagePane
object is added so that it fills the center of the dialog window. The
buttonPane
position is specified as
BorderLayout.SOUTH
, so it will be at the bottom of the dialog window. Both
JPanel
objects have a
FlowLayout
manager by default.
We want the
AboutDialog
object to be the listener for the
OK
button so we pass the
this
variable as
the argument to the
addActionListener()
method call for the button.
The
pack()
method is inherited from the
Window
class. This method packs the components in the
window, setting the window to an optimal size for the components it contains. Note that if you don't call
pack()
here, the size for your dialog will not be set and you won't be able to see it.
The
actionPerformed()
method will be called when the
OK
button is selected. This just disposes of
the dialog by calling the
dispose()
method for the
AboutDialog
object so the dialog window will
disappear from the screen and the resources it was using will be released.
To add a
Help
menu with an
About
item to our Sketcher application, we need to insert some code into
the
SketchFrame
class constructor.
Try It Out - Creating an About Menu Item
You shouldn't have any trouble with this. We can make the
SketchFrame
object the listener for the
About
menu item so add
ActionListener
to the list of interfaces implemented by
SketchFrame
:
public class SketchFrame extends JFrame implements Constants, ActionListener {
The changes to the constructor to add the
Help
menu will be:
public SketchFrame(String title , Sketcher theApp) {
setTitle(title); // Set the window title
this.theApp = theApp;
setJMenuBar(menuBar); // Add the menu bar to the window
setDefaultCloseOperation(EXIT
_
ON
_
CLOSE); // Default is exit the application
JMenu fileMenu = new JMenu("File"); // Create File menu
JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
JMenu helpMenu = new JMenu("Help"); // Create Help menu
fileMenu.setMnemonic('F'); // Create shortcut
elementMenu.setMnemonic('E'); // Create shortcut
helpMenu.setMnemonic('H'); // Create shortcut