Home Segments Top Top Previous Next

957: Mainline

Next, you create a listener that pops up the menu when you click the mouse. The listener should implement the MouseListener interface, which insists that you define methods, often empty, for responding to all possible mouse events, as well as to the one of interest. Alternatively, you can implement the interface indirectly, by extending the MouseAdapter class, which implements empty methods for all the methods required by the interface.

The mouse event that is of interest is the mouseClicked event. In response, the show method displays the popup menu at a specified position relative to the clicked component. The getX and getY methods return the coordinates of the mouse pointer at the time the mouse is clicked; thus, the popup menu appears at those coordinates.

import java.awt.event.*; 
import javax.swing.*; 
public class MovieMouseListener extends MouseAdapter {              
 private MovieApplication applet; 
 public MovieMouseListener (MovieApplication a) { 
  applet = a; 
 } 
 public void mouseClicked (MouseEvent e) {                       
  MoviePopupMenu menu = new MoviePopupMenu(applet); 
  menu.show((JComponent)(e.getSource()), e.getX(), e.getY());  
 } 
}