Please excuse the vague question title, but usually I don't do such kind of stuff. So I have the fo开发者_如何学编程llowing 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. In reality, I want not only two such actions, but some dozen of them.
The problem is the cleanup
thing. cleanup
should be after any of these actions has been chosen. This means, if I continue in the abovely described manner, I will have to write cleanup()
for each AbstractAction
.
Is there any (easy/elegant/nice) way or pattern to avoid writing cleanup()
over and over again? I.e. is it possible to desing something that will only get the action and after executing it automatically call 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();
}
});
精彩评论