/*
Note: The version of this example in the 2nd edition printing has
a serious flaw. It failes to register the buttons individually as
MouseListeners.
*/
import java.awt.*;
import java.awt.event.*;
public class PopupColorMenu extends java.applet.Applet implements ActionListener {
PopupMenu colorMenu;
Component selectedComponent;
public void init() {
MouseAdapter adapter = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if ( e.isPopupTrigger() ) {
selectedComponent = getComponentAt( e.getX(), e.getY() );
colorMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
};
Button button = new Button("One");
button.addMouseListener( adapter );
add( button );
button = new Button("Two");
button.addMouseListener( adapter );
add( button );
button = new Button("Three");
button.addMouseListener( adapter );
add( button );
colorMenu = new PopupMenu("Color");
colorMenu.add( makeMenuItem("Red") );
colorMenu.add( makeMenuItem("Green") );
colorMenu.add( makeMenuItem("Blue") );
add(colorMenu);
}
public void actionPerformed(ActionEvent e) {
String color = e.getActionCommand();
if ( color.equals("Red") )
selectedComponent.setBackground( Color.red );
else if ( color.equals("Green") )
selectedComponent.setBackground( Color.green );
else if ( color.equals("Blue") )
selectedComponent.setBackground( Color.blue );
}
private MenuItem makeMenuItem(String label) {
MenuItem item = new MenuItem(label);
item.addActionListener( this );
return item;
}
}
|