import java.awt.event.*;
import java.beans.*;
import javax.swing.*;

/**
 * An ActionForwarder keeps track of which GUI Component has the
 * focus and forwards actionPerformed messages to the appropriate
 * Component.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ActionForwarder implements ActionListener, PropertyChangeListener
{
  private JComponent focusOwner;
  
  /**
   * Default Constructor.
   */
  public ActionForwarder()
  {
    focusOwner = null;
  }

  /**
   * Handle propertyChange messages. Specifically, keep track of
   * the Component with the focus.
   * 
   * @param pce  The event that generated the message
   */
  public void propertyChange(PropertyChangeEvent pce) 
  {
    Object source = pce.getNewValue();
    
    if (source instanceof JComponent) 
    {
        focusOwner = (JComponent)source;
    }
    else
    {
        focusOwner = null;
    }
  }

  /**
   * Handle actionPerformed messages. Specifically, forward them to
   * the Component with the focus (if that Component has an
   * appropriate Action).
   * 
   * @param ae The event that generated the message.
   */
  public void actionPerformed(ActionEvent e) 
  {
    if (focusOwner == null) return;
    
    String actionCommand = (String)e.getActionCommand();
    Action action = focusOwner.getActionMap().get(actionCommand);
    if (action != null) 
    {
      action.actionPerformed(new ActionEvent(focusOwner, ActionEvent.ACTION_PERFORMED, null));
    }
  }
}
