Java Reference
In-Depth Information
if (background != null) {
button.setBackground(background);
}
}
};
button.addActionListener(actionListener);
frame.add(button, BorderLayout.CENTER);
frame.setSize(300, 100);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Providing Your Own OK/Cancel Event Listeners
If the showDialog() method provides too much automatic behavior, you may prefer another
JColorChooser method that allows you to customize the chooser before displaying it and define
what happens when the OK and Cancel buttons are selected:
public static JDialog createDialog(Component parentComponent, String title,
boolean modal, JColorChooser chooserPane, ActionListener okListener,
ActionListener cancelListener)
In createDialog() , the parent component and title arguments are the same as showDialog() .
The modal argument allows the pop-up window to be nonmodal, unlike showDialog() in
which the pop-up is always modal. When the pop-up is not modal, the user can still interact
with the rest of the application. The OK and Cancel buttons in the pop-up window automati-
cally have one associated ActionListener that hides the pop-up window after selection. It's
your responsibility to add your own listeners if you need any additional response from selection.
To demonstrate proper usage of createDialog() , the program shown in Listing 9-10 dupli-
cates the functionality of the program shown in Listing 9-9. However, instead of automatically
accepting the new color, the color change is rejected if the new background is the same color
as the foreground. In addition, if the user selects the Cancel button, the button background
color is set to red.
Listing 9-10. Custom Action Listeners on JColorChooser Buttons
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
public class CreateColorSamplePopup {
Search WWH ::




Custom Search