Listener Pattern

Intent

To allow only those objects that are interested in events to register for them.

Motivation

Structure

Adding a MouseListener to a Java AWT Component (example from Latrunculi)

Sample Code

As taken from Latrunculi project

public class LVBoard extends JPanel{
      public LVBoard(LVArena own){
          myOwner = own;
      // Use the border factory to share borders
          setBorder(BorderFactory.createMatteBorder(BORDER_TOP,BORDER_LEFT,
                      BORDER_BOTTOM,BORDER_RIGHT,Color.red));
          addMouseListener(new BoardListener());

      }
/*  A very standard mouse listener. The only event we care about is the click.
    As is normal, we route the call straight back to the LVBoard class.
*/
      class BoardListener implements java.awt.event.MouseListener{
          public void mouseClicked(MouseEvent e){
              mouseHasBeenClicked(e);
          }
          public void mouseEntered(MouseEvent e){
          }      // not interested, so null
          public void mouseExited(MouseEvent e){
          }
          public void mousePressed(MouseEvent e){
          }
          public void mouseReleased(MouseEvent e){
          }
      }
	  
      // Figure out the square the click occurred in and tell the model
      void mouseHasBeenClicked(MouseEvent e){
          int row = (e.getY()- getBorder().getBorderInsets(this).top)/rowHeight;
          int col = (e.getX()- getBorder().getBorderInsets(this).top)/colWidth;
          myOwner.getModel().mouseClick(new Location(row,col));
      }