AbstractAction as WindowListener
Asked Answered
B

1

7

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?

Bringhurst answered 8/5, 2012 at 1:37 Comment(0)
E
6

Forwarding events is handy, but you can also use dispatchEvent(), as shown here.

Addendum: More examples that use Action are shown below.

Elyn answered 8/5, 2012 at 1:54 Comment(4)
A related approach is to invoke a button's doClick() method, as shown here.Elyn
This thing is something new for me, and quite interesting :-)Hallie
So, if I understand it correctly, using dispatchEvent() is sort of the opposite of what I'm doing: keeping the code in the WindowListener instead of in an action, and making the action send an event there instead of making the windowListener forward it's event to the action? Interesting...Bringhurst
I can see the symmetry; more above.Elyn

© 2022 - 2024 — McMap. All rights reserved.