Java Reference
In-Depth Information
}
// makePopup
/** Change background color of selected components. **/
public void actionPerformed (ActionEvent e)
{
String color
=
e.getActionCommand ();
if (color.equals (
"
Red
"
))
fSelectedComponent.setBackground (Color.red);
else if(color.equals (
"
Green
"
))
fSelectedComponent.setBackground (Color.green);
else if (color.equals (
"
Blue
"
))
fSelectedComponent.setBackground (Color.blue);
else
setBackground (Color.white);
}
// actionPerformed
/** A utility method for making menu items. **/
private JMenuItem makeMenuItem (String label)
{
JMenuItem item
=
new JMenuItem (label);
item.addActionListener (this);
return item;
}
}
// class PopupPanel
The applet's interface consists of an instance of a subclass of
JPanel
called
PopupPanel
to which two subpanels are added. An instance of a
Mouse-
Adapter
subclass, using the anonymous inner class technique, is created and
added to the
MouseListener
list of both panels. Mouse clicks therefore go to
the adapter, which looks for the popup menu request. If detected, then an instance
of
JPopupMenu
with the color menu items is displayed. (Systems differ as to
whether the popup signal is generated on a mouse button press or release so
both are tested here.) When the user selects an item in the popup menu list,
the
actionPerformed()
method is invoked and the background color is set
according to which menu item was selected and over which panel.
Note that you don't necessarily need to use a
JPopupMenu
object in response
to an affirmative
isPopupTrigger()
response. You could always open a dialog
window instead. For example, you could create a popup dialog for a
JTextField
to allow the user to enter a new value for some parameter that you clicked on.
12.6 Handling keystrokes
Just as you can catch mouse button clicks, you can also identify which key the user
struck. A class that implements the
KeyListener
interface must provide the
Search WWH ::
Custom Search