
46
|
Chapter 1, Basic JComponents
#10 Building a Drop-Down Menu Button
HACK
With the code so far, you can show the pop-up window. To close it, you
must listen for ancestor events to find out when something above the drop-
down in the component tree has changed. They all just call
hidePopup( )
to
safely turn it off:
public void ancestorAdded(AncestorEvent event){
hidePopup( );
}
public void ancestorRemoved(AncestorEvent event){
hidePopup( );
}
public void ancestorMoved(AncestorEvent event){
if (event.getSource( ) != popup) {
hidePopup( );
}
}
public void hidePopup( ) {
if(popup != null && popup.isVisible( )) {
popup.setVisible(false);
}
}
Adding a Color Selection Panel
With the DropDownComponent finished, you can finally build something with
it. For this hack, I’ve chosen a color selector. This is a small widget that lets
the user pick one of 12 standard colors without having to open up a full
color chooser. Most word processors and spreadsheets have a component
like this, so there’s no reason for Swing not to have one, too.
ColorSelectionPanel, shown in Example 1-22, is just a JPanel with a 4 × 3
grid of buttons. Each button represents one of the most common 10 colors,
plus black and white. When a color button is clicked, it will call
selectColor( ) to fire off a color selection event.
Example 1-22. A color selection panel to be used in the drop-down component
public class ColorSelectionPanel extends JPanel ...