28.12.2012 Views

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

818 Chapter 7 Using Standard Dialogs<br />

2. Get a reference to its ColorSelectionModel and register a<br />

listener with it.<br />

3. Display the dialog.<br />

4. While the dialog is displayed, react to color changes by adjusting<br />

the image (or whatever else the color change should apply<br />

to).<br />

5. When the dialog is dismissed, if the user pressed Cancel and<br />

any changes were made to the image, restore the original color.<br />

None of this is actually very difficult to achieve. Listing 7-15 shows an<br />

example that uses this technique to keep the background color of a frame in<br />

step with the color selected in a color chooser.<br />

Listing 7-15 Handling JColorChooser Events<br />

package <strong>JFC</strong>Book.Chapter7;<br />

import javax.swing.*;<br />

import j avax.swing.colorchooser.*;<br />

import javax.swing.event.*;<br />

import j ava.awt.*;<br />

import java.awt.event.*;<br />

public class ColorChooserExample2 {<br />

public static void main(String[J args) {<br />

final JFrame parentFrame =<br />

new JFrame("Color Chooser Example 2");<br />

parentFrame.getContentPane().setBackground(<br />

Color.black);<br />

parentFrame.setSize(300, 300);<br />

parentFrame.setVisible(true);<br />

parentFrame.getContentPane().addMouseListener(<br />

new MouseAdapter() {<br />

public void mousePressed(MouseEvent evt) {<br />

final Color originalColor =<br />

parentFrame.getContentPane () .getBackground () ;<br />

final JColorChooser chooser =<br />

new JColorChooser(originalColor)<br />

final ColorSelectionModel model =<br />

chooser.getSelectionModel0;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!