下面对菜单项添加操作事件的监听器接口。比如点击打开菜单项后,弹出文件对话框并根据用户选择打开对应的文件。
要达到这目标的,需要使用接收操作事件的侦听器接口ActionListener。组件类实现该接口后,使用addActionListener方法向该组件注册。当对应的操作时间发生时,该组件对象的actionPerformed方法将被调用,以实现相应的操作要求。该类的详细介绍,可猛击这里。
例如本编辑器MEditor实现了ActionListener接口,若每个菜单项JMenuItem使用addActionListener方法向MEditor注册事件监听,当菜单操作时间发生时,将会有actionPerformed方法被激发以实现相应的菜单操作。
下面开始添加事件监听功能:
第一步,实现ActionListener接口。如下:
- public class MEditor implements ActionListener {
-
- ...
-
- }
第二步,在菜单项中注册操作事件。由于菜单统一由根菜单(如FileMenu)进行管理,可考虑添加一方法对整个菜单树添加。如此,在EditorMenu.java中添加此方法的描述并在FileMenu.java中进行实现。代码修改如下:
- public interface EditorMenu{
-
-
-
-
-
- public void registerActionListener(MEditor editor);
-
- }
- public class FileMenu extends JMenu implements EditorMenu {
-
-
-
-
-
- public void registerActionListener(MEditor editor) {
- menuFileNew.addActionListener(editor);
- menuFileOpen.addActionListener(editor);
- }
-
- ...
- }
第三步,实现actionPerformed方法以完成对事件操作的响应。修改MEditor.java的代码如下:
- public class MEditor implements ActionListener {
-
- ...
-
- public void createWindow() {
-
-
- MenuFactory fileMenuFactory = new FileMenuFactory();
- fileMenu = fileMenuFactory.getMenuInstance();
-
-
- fileMenu.registerActionListener(this);
- ...
- }
-
-
-
-
- public void actionPerformed(ActionEvent event) {
-
- ...
- }
- }