在SWT中处理关闭红色X按钮的问题

时间:2014-01-11 23:58:51

标签: java swt serversocket

我有一个关于右上角红色按钮的快速问题来关闭应用程序(Windows 7)... 我用Java编写了一个ServerSocket但是当我使用这个关闭按钮关闭应用程序时,服务器继续运行...... 我想捕获此事件(如果可能),并确保按下此按钮时,包括ServerSocket在内的整个程序都将关闭。

这是我认为必须修改以捕获此事件的代码片段......

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

任何帮助将不胜感激...... 谢谢!

2 个答案:

答案 0 :(得分:1)

SWT.Close上收听Display并在此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();
        }
    }
}

答案 1 :(得分:-1)

您可以将WindowListener附加到它并在windowClosing()方法中放置您需要做的任何事情。

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) {

}

}