Java Reference
In-Depth Information
// Add the menu item listeners
moveItem.addActionListener(this);
deleteItem.addActionListener(this);
rotateItem.addActionListener(this);
sendToBackItem.addActionListener(this);
}
We add the menu items using the add() method that accepts a String argument, and returns a
reference to the JMenuItem object that it creates. We then use these references to add the view object
as the listener for all the menu items in the pop-up.
We must make sure the SketchView class declares that it implements the ActionListener
interface:
class SketchView extends JComponent
implements Observer, Constants, ActionListener {
We can add the actionPerformed() method to SketchView that will handle action events from
the menu items.
As with the new data members above, be careful to add this to the SketchView class
and not inside the inner MouseHandler class by mistake!
public void actionPerformed(ActionEvent e ) {
Object source = e.getSource();
if(source == moveItem) {
// Process a move...
} else if(source == deleteItem) {
// Process a delete...
} else if(source == rotateItem) {
// Process a rotate
} else if(source == sendToBackItem) {
// Process a send-to-back...
}
}
Of course, we will need two more import statements in the SketchView.java file:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
To pop the menu we need to modify the code in the mouseReleased() method of the
MouseHandler inner class a little:
Search WWH ::




Custom Search