Java:WindowAdapter windowClosed 方法未运行



我目前正在扩展JFrame的类中运行它。关闭窗口时,我在控制台中看不到RAN EVENT HANDLER。这不是主窗口,此窗口的多个实例可以同时存在。

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

此方法位于构造函数中调用的名为 initialiseEventHandlers() 的方法中,因此我确定代码正在运行。

我做错了什么?

谢谢!

编辑:这是完整的(摘要)代码:

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

我发现我使用了错误的方法:windowClosed()。我应该使用windowClosing()

这应该有效

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

将其添加到构造函数中。

setDefaultCloseOperation(EXIT_ON_CLOSE);

下面的

代码对我有用。

// 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

相关内容

  • 没有找到相关文章

最新更新