Java Reference
In-Depth Information
// Handle About menu action events
public void actionPerformed(ActionEvent e) {
if(e.getSource() == aboutItem) {
// Create about dialog with the menu item as parent
JOptionPane.showMessageDialog(this, // Parent
"Sketcher Copyright Ivor Horton 2001", // Message
"About Sketcher", // Title
JOptionPane.INFORMATION
_
MESSAGE); // Message type
} else if(e.getSource() == fontItem) { // Set the dialog window position
Rectangle bounds = getBounds();
fontDlg.setLocation(bounds.x + bounds.width/3, bounds.y + bounds.height/3);
fontDlg.setVisible(true); // Show the dialog
} else if(e.getSource() == customColorItem) {
Color color = JColorChooser.showDialog(this, "Select Custom Color",
elementColor);
if(color != null) {
elementColor = color;
statusBar.setColorPane(color);
}
}
}
With the
JColorChooser
class imported, recompile and rerun Sketcher and select the
Custom
Color...
menu item from the general pop-up. You will see the dialog below.
How It Works
The
JColorChooser
class defines a complete color choosing facility that you can use in your own dialog,
or create a complete modal dialog by calling the
static
method
showDialog()
as we have done here.
The arguments to
showDialog()
are a reference to the parent component for the dialog, the title for the
dialog, and the initial color selection. You can choose a color using any of the three tabs that provide
different mechanisms for defining the color that you want. When you click on
OK,
the color that you chose is
returned as type
Color
. Exiting the dialog by any other means than selecting the
OK
button returns
null
.
We just store the color returned in
elementColor
, and set it in the status bar pane.