| JColorChooser |
|---|
JColorChooser is a component that is new to Swing; there
is no AWT equivalent. It lets the user interactively select a
Color. The default behavior is to present a dialog box
containing a tabbed pane letting the user choose via swatches, HSB
values, or RGB values.
The simplest use is very simple indeed; call
JColorChooser.showDialog, supplying three arguments. The
first argument is the parent Component, the second is the
title, and the third is the initially selected color. If the user
selects "OK," the return value is the Color
chosen. If the user cancels, the return value is null.
You can also allocate JColorChooser via a
constructor. This is common if you want to display it somewhere other
than in a popup dialog, or if you are likely to pop it up many
times. In the latter case, pass the JColorChooser
instance to JColorChooser.createDialog.
The following example creates a small JFrame with a
button that pops up a JColorChooser. The background color
of the content pane is set to the color selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JColorChooserTest extends JFrame
implements ActionListener {
public static void main(String[] args) {
new JColorChooserTest();
}
public JColorChooserTest() {
super("Using JColorChooser");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton colorButton
= new JButton("Choose Background Color");
colorButton.addActionListener(this);
content.add(colorButton);
setSize(300, 100);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Args are parent component, title, initial color
Color bgColor
= JColorChooser.showDialog(this,
"Choose Background Color",
getBackground());
if (bgColor != null)
getContentPane().setBackground(bgColor);
}
}
Note: also requires
WindowUtilities.java
and ExitListener.java,
shown earlier.