| |
e876. Creating a JColorChooser Dialog
The following example creates a temporary color chooser dialog and
shows it:
Color initialColor = Color.red;
// Show the dialog; this method does not return until the dialog is closed
Color newColor = JColorChooser.showDialog(frame, "Dialog Title", initialColor);
Here is a more elaborate example that defines an action that creates
and shows a color chooser dialog. This action can be used in
components such as a button or a menu item.
// This action creates and shows a modeless color chooser dialog.
public class ShowColorChooserAction extends AbstractAction {
JColorChooser chooser;
JDialog dialog;
ShowColorChooserAction(JFrame frame, JColorChooser chooser) {
super("Color Chooser...");
this.chooser = chooser;
// Choose whether dialog is modal or modeless
boolean modal = false;
// Create the dialog that contains the chooser
dialog = JColorChooser.createDialog(frame, "Dialog Title", modal,
chooser, null, null);
}
public void actionPerformed(ActionEvent evt) {
// Show dialog
dialog.setVisible(true);
// Disable the action; to enable the action when the dialog is closed, see
// e884 Listening for OK and Cancel Events in a JColorChooser Dialog
setEnabled(false);
}
};
Here's some code that demonstrates the use of the action:
JFrame frame = new JFrame();
// Create a color chooser dialog
Color initialColor = Color.white;
JColorChooser chooser = new JColorChooser(initialColor);
// Create a button using the action
JButton button = new JButton(new ShowColorChooserAction(frame, chooser));
e877.
Getting and Setting the Selected Color in a JColorChooser Dialog
© 2002 Addison-Wesley.
|