I have a quick question regarding upper right corner red button to close the applications (Windows 7)... I have programmed a ServerSocket in Java but when I close the application using this close button the server keeps running... I would like to capture this event (if possible), and ensure that when this button is pressed the whole program including the ServerSocket is closed.
This is the piece of code I think that I have to amend to capture this event...
public static void main(String[] args) {
try {
new Server().startServer();
Window1 window = new Window1();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
Any help will be appreciated... Thanks!
Listen for SWT.Close
on your Display
and shut the server down within this Listener
:
public static void main(String[] args) {
try {
new Server().startServer();
Window1 window = new Window1();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void shutdownServer()
{
/* Shutdown your server here */
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
display.addFilter(SWT.Close, new Listener()
{
@Override
public void handleEvent(Event arg0)
{
shutdownServer();
}
});
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
You can attach a WindowListener to it and put whatever you need to do in the windowClosing() method.
public class Test implements WindowListener {
public static void main(String[] args) {
}
public Test() {
final JFrame frame = new JFrame();
frame.addWindowListener(this);
}
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
//handle window closing, close socket, etc
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.