Java Reference
In-Depth Information
public class SketchFrame extends Jframe implements Constants {
// SketchFrame class as before...
// Class defining a general purpose message box
class AboutDialog extends JDialog implements ActionListener {
public AboutDialog(Frame parent, String title, String message) {
super(parent, title, true);
// If there was a parent, set dialog position inside
if(parent != null) {
Dimension parentSize = parent.getSize(); // Parent size
Point p = parent.getLocation(); // Parent position
setLocation(p.x+parentSize.width/4,p.y+parentSize.height/4);
}
// Create the message pane
JPanel messagePane = new JPanel();
messagePane.add(new JLabel(message));
getContentPane().add(messagePane);
// Create the button pane
JPanel buttonPane = new JPanel();
JButton button = new JButton("OK"); // Create OK button
buttonPane.add(button); // add to content pane
button.addActionListener(this);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
setDefaultCloseOperation(DISPOSE
_
ON
_
CLOSE);
pack(); // Size window for components
setVisible(true);
}
// OK button action
public void actionPerformed(ActionEvent e) {
setVisible(false); // Set dialog invisible
dispose(); // Release the dialog resources
}
}
}
How It Works
The constructor first calls the base
JDialog
class constructor to create a modal dialog with the title bar given
by the
title
argument. It then defines the position of the dialog relative to the position of the frame.
When we create an instance of the
AboutDialog
class in the Sketcher program a
little later in this chapter, we'll specify the
SketchFrame
object as the parent for the
dialog. The parent relationship between the application window and the dialog implies
a lifetime dependency. When the
SketchFrame
object is destroyed, the
AboutDialog
object will be too, because it is a child of the
SketchFrame
object.
This doesn't just apply to
JDialog
objects - any
Window
object can have another
Window
object as a parent.