简体   繁体   English

任何 AbstractAction 执行后都应调用特殊方法

[英]Special method should be called after any AbstractAction-execution

Please excuse the vague question title, but usually I don't do such kind of stuff.请原谅模糊的问题标题,但通常我不做这种事情。 So I have the following problem:所以我有以下问题:

I'm designing a popupmenu for a specific app where each menu item is associated with a certain action:我正在为特定应用程序设计一个弹出菜单,其中每个菜单项都与某个操作相关联:

public class CanvasMenu extends JPopupMenu {        
    public CanvasMenu(){
       this.add(new AbstractAction("Do some operation") {
           @Override
           public void actionPerformed(ActionEvent arg0) {
                doSomeStuff1();
                cleanup(); // has to be done after every menu operation
           }
    });

        this.add(new AbstractAction("Other operation") {
            @Override
            public void actionPerformed(ActionEvent e) {
                doSomeOtherStuff();
                cleanup(); // has to be done after every menu operation
            }
        });
    }
}

I read somewhere that AbstractAction is used for such tasks where you want to add menu items and associate them with some action.我在某处读到AbstractAction用于您想要添加菜单项并将它们与某些操作相关联的任务。 In reality, I want not only two such actions, but some dozen of them.实际上,我想要的不仅仅是两个这样的动作,而是几十个。

The problem is the cleanup thing.问题是cleanup的事情。 cleanup should be after any of these actions has been chosen. cleanup应该在选择了这些操作中的任何一个之后进行。 This means, if I continue in the abovely described manner, I will have to write cleanup() for each AbstractAction .这意味着,如果我以上述方式继续,我将不得不为每个AbstractAction编写cleanup()

Is there any (easy/elegant/nice) way or pattern to avoid writing cleanup() over and over again?是否有任何(简单/优雅/漂亮)的方式或模式来避免一遍又一遍地编写cleanup() Ie is it possible to desing something that will only get the action and after executing it automatically call cleanup ?即是否有可能设计一些只会获得动作并在执行后自动调用cleanup的东西?

This is one of the patterns:这是其中一种模式:

abstract class ActionWithCleanup extend AbstractAction {
       @Override
       public final void actionPerformed(ActionEvent arg0) {
            myAction();
            cleanup(); // has to be done after every menu operation
       }

       public abstract void myAction();
}

... ...

this.add(new ActionWithCleanup("Do some operation") {
       @Override
       public void myAction() {
            doSomeStuff1();
       }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM