Search code examples
javaevent-handlingwindowlistener

Java: WindowAdapter windowClosed method not running


I'm currently running this in a class that extends a JFrame. When I close the window, I don't see RAN EVENT HANDLER in the console. This is not the main window, and more than one instance of this window can exist at the same time.

    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {
            System.out.println("RAN EVENT HANDLER");
        }
    });

This method is inside a method called initialiseEventHandlers() which is called in the constructor, so I'm sure the code is running.

What am I doing wrong?

Thank you!

EDIT: Here's the full (summarised) code:

public class RacesWindow extends JFrame {

private JPanel mainPanel;
private JLabel lblRaceName;
private JTable races;
private DefaultTableModel racesModel;

public RacesWindow() {
    this.lblRaceName = new JLabel("<html><strong>Race: " + race.toString()
            + "</strong></html>");
    initialiseComponents();
    this.setMinimumSize(new Dimension(500, 300));
    this.setMaximumSize(new Dimension(500, 300));
    initialiseEventHandlers();
    formatWindow();
    pack();
    setVisible(true);
}

public void initialiseComponents() {
    mainPanel = new JPanel(new BorderLayout());
    races = new JTable();
    racesModel = new DefaultTableModel();
    races.setModel(racesModel);
}

public void initialiseEventHandlers() {
    System.out.println("EVENTHANDLER CODE IS CALLED"); //for debugging
    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {
            System.out.println("RAN EVENT HANDLER");
            appManager.removeOpenWindow(race.toString());
        }
    });
}}


public void formatWindow() {
    mainPanel.add(lblRaceName, BorderLayout.NORTH);
    mainPanel.add(new JScrollPane(races), BorderLayout.CENTER);
    mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
    this.add(mainPanel);
}
}

Solution

  • I found out I was using the wrong method: windowClosed(). I should use windowClosing()!