Search code examples
javaawtframemenuitemwindowlistener

Can I add a WindowListener to a MenuItem?


I have a program written in AWT, so I am using Frame (Not JFrame/Swing). I am using MenuItem objects to do some operations through ActionListeners.

However, on my last MenuItem, I want to use a WindowListener to close the frame (intending to close the frame without terminating the program altogether).

I am aware that the MenuItem documentation doesn't have a addWindowListener() method. But is there a way around that?

f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
    f.dispose();
}});

This is pretty much what I'm trying to do, but from a MenuItem.


Solution

  • The window listener is not about making the window close - it's a set of callbacks that happen when a window does particular things. From the Javadoc:

    When the window's status changes by virtue of being opened, closed, activated or deactivated, iconified or deiconified, the relevant method in the listener object is invoked, and the WindowEvent is passed to it.

    windowClosing has the following Javadoc:

    void windowClosing(WindowEvent e)
    Invoked when the user attempts to close the window from the window's system menu.

    If you want to programatically close the window when someone clicks the menu item, then simply add an action listener with the following:

    f.setVisible(false);
    f.dispose();