Reputation: 425
Basically it's a client program with a GUI so I want to close the sockets when the user closes the client program. Is there is Listener or something that will allow me to do this?
Upvotes: 0
Views: 189
Reputation: 1460
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// do stuff
}
});
Note that this will only be called when the default close operation has been set to EXIT_ON_CLOSE
before the frame is closed via the (x) button. The default is HIDE_ON_CLOSE
which technically does not close the window, therefore the listener would not be notified.
Upvotes: 2
Reputation: 8247
Add a WindowListener
for the closing event:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
// Do stuff
}
});
For more help, look at this tutorial on WindowListener
's.
Upvotes: 2
Reputation: 39960
To refer to this
from an enclosing scope, use 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);
// ...
}
}
}
Or store it in a variable with a different name:
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);
// ...
}
}
}
Upvotes: 1