Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AbstractAction as WindowListener

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?

like image 433
Erik Stens Avatar asked May 08 '12 01:05

Erik Stens


1 Answers

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.
like image 136
trashgod Avatar answered Oct 20 '22 06:10

trashgod