下面对菜单项添加操作事件的监听器接口。比如点击打开菜单项后,弹出文件对话框并根据用户选择打开对应的文件。
  要达到这目标的,需要使用接收操作事件的侦听器接口ActionListener。组件类实现该接口后,使用addActionListener方法向该组件注册。当对应的操作时间发生时,该组件对象的actionPerformed方法将被调用,以实现相应的操作要求。该类的详细介绍,可猛击这里

  例如本编辑器MEditor实现了ActionListener接口,若每个菜单项JMenuItem使用addActionListener方法向MEditor注册事件监听,当菜单操作时间发生时,将会有actionPerformed方法被激发以实现相应的菜单操作。

  下面开始添加事件监听功能:
  第一步,实现ActionListener接口。如下:
  1. public class MEditor implements ActionListener { 
  2.  
  3.     ... 
  4.  
  第二步,在菜单项中注册操作事件。由于菜单统一由根菜单(如FileMenu)进行管理,可考虑添加一方法对整个菜单树添加。如此,在EditorMenu.java中添加此方法的描述并在FileMenu.java中进行实现。代码修改如下:
  1. public interface EditorMenu{ 
  2.  
  3.     /** 
  4.      * 描述对每个菜单项添加事件监听器的方法 
  5.      * @param editor 
  6.      */ 
  7.     public void registerActionListener(MEditor editor); 
  8.  
  1. public class FileMenu extends JMenu implements EditorMenu { 
  2.  
  3.     /** 
  4.      * 为每个菜单项添加事件监听器 
  5.      * @param editor 
  6.      */ 
  7.     public void registerActionListener(MEditor editor) { 
  8.         menuFileNew.addActionListener(editor); 
  9.      menuFileOpen.addActionListener(editor); 
  10.     } 
  11.  
  12.     ... 
  第三步,实现actionPerformed方法以完成对事件操作的响应。修改MEditor.java的代码如下:
  1. public class MEditor implements ActionListener { 
  2.  
  3.     ... 
  4.  
  5.     public void createWindow() { 
  6.  
  7.         // 利用工厂方法生成菜单项 
  8.      MenuFactory fileMenuFactory = new FileMenuFactory(); 
  9.      fileMenu = fileMenuFactory.getMenuInstance(); 
  10.  
  11.         // 为菜单项注册操作事件监听器 
  12.      fileMenu.registerActionListener(this); 
  13.         ... 
  14.     } 
  15.  
  16.     /** 
  17.      * 实现ActionListener的事件响应方法 
  18.      */ 
  19.     public void actionPerformed(ActionEvent event) { 
  20.      
  21.         ...  
  22.     } 
  23. }