AbstractAction as WindowListener

南楼画角 提交于 2019-12-28 06:23:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!