Java: WindowAdapter windowClosed method not running

妖精的绣舞 提交于 2020-01-17 01:46:23

问题


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);
}
}

回答1:


This should work

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



回答2:


Add this to your constructor.

setDefaultCloseOperation(EXIT_ON_CLOSE);




回答3:


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




回答4:


The code below worked for me.

// parent class {
     // constructor {      
     ...    
        this.addWindowListener(new GUIFrameListener());
     ...
    }
    class GUIFrameListener extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            System.out.println("Window Closed");
        }
    }
} // end of parent class


来源:https://stackoverflow.com/questions/22193920/java-windowadapter-windowclosed-method-not-running

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