Java Reference
In-Depth Information
When called, showDialog() creates a modal dialog box with the given parent component
and title. Within the dialog box is a JColorChooser whose initial color is the one provided. As
you can see in Figure 9-18 (shown earlier in the chapter), along the bottom are three buttons:
OK, Cancel, and Reset. When OK is pressed, the pop-up window disappears and the showDialog()
method returns the currently selected color. When Cancel is pressed, null is returned instead
of the selected color or the initial color. Selection of the Reset button causes the JColorChooser
to change its selected color to the initial color provided at startup.
What normally happens with the showDialog() method is that the initial color argument is
some color property of an object. The returned value of the method call then becomes the new
setting for the same color property. This usage pattern is shown in the following lines of code,
where the changing color property is the background for a button. As with JOptionPane , the
null parent-component argument causes the pop-up window to be centered on the screen
instead of over any particular component.
Color initialBackground = button.getBackground();
Color background = JColorChooser.showDialog(
null, "Change Button Background", initialBackground);
if (background != null) {
button.setBackground(background);
}
To place this code in the context of a complete example, Listing 9-9 shows source code
that offers a button that, when selected, displays a JColorChooser . The color selected within the
chooser becomes the background color of the button after the OK button is selected.
Listing 9-9. Using showDialog with the JColorChooser
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorSamplePopup {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("JColorChooser Sample Popup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button = new JButton("Pick to Change Background");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Color initialBackground = button.getBackground();
Color background = JColorChooser.showDialog(
null, "Change Button Background", initialBackground);
Search WWH ::




Custom Search