问题
I'm trying to separate function from state in my GUI application by the use of Action objects. I've been successful in using these to create menu items and buttons that have the same functionality.
My problem is this: I want to have the same Action for both the 'exit' item in my menu and the close button of the frame.
Currently I've been able to solve it by adding the following WindowListener to the frame:
private class MainWindowListener extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
new ExitAction(model).actionPerformed(new ActionEvent(e.getSource(), e.getID(), "Exit"));
}
}
Isn't there a simpler more straightforward way to do this?
回答1:
Forwarding events is handy, but you can also use dispatchEvent()
, as shown here.
Addendum: More examples that use Action are shown below.
- LinePanel which connects buttons and keys.
- ScrollAction which leverages existing Swing actions.
- KeyPadPanel which illustrates forwarding actions.
- GraphPanel which shows graph editor actions in a tool bar.
来源:https://stackoverflow.com/questions/10491400/abstractaction-as-windowlistener