用户关闭(Xs out)JFrame后立即执行操作

基本上它是一个带有GUI的客户端程序,所以我想在用户关闭客户端程序时关闭套接字。 是否有监听器或某些东西可以让我这样做?

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // do stuff } }); 

请注意, 只有在通过(x)按钮关闭帧之前将默认关闭操作设置为EXIT_ON_CLOSE才会调用此方法。 默认为HIDE_ON_CLOSE ,从技术上讲不关闭窗口,因此不会通知监听器。

为结束事件添加一个WindowListener

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { // Do stuff } }); 

有关更多帮助,请查看WindowListener的本教程 。

要从封闭范围引用this ,请使用以下命令:

 class MyFrame extends JFrame { public MyFrame() { this.addWindowListener( // omitting AIC boilerplate // Use the name of the enclosing class MyFrame.this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // ... } } } 

或者将其存储在具有不同名称的变量中:

 class MyFrame extends JFrame { public MyFrame() { final JFrame thisFrame = this; this.addWindowListener( // omitting AIC boilerplate // Use the name of the enclosing class thisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // ... } } }