WindowAdapter调度窗口事件(关闭窗口)

时间:2016-04-26 21:13:09

标签: java swing

我创建了一个从WindowAdapter扩展的类,这样每次我想关闭一个窗口时,它会询问你是否真的要关闭窗口。当我点击"否"时出现问题。如何处理它以使窗口事件不会保持"那里和框架一直试图发送它? 我只回报,我无法想出任何东西。这是代码:

public class ExitController extends WindowAdapter{

    @Override
    public void windowClosing(WindowEvent windowEvent) {
        if(JOptionPane.showConfirmDialog(null,"Are you sure to close this window?", 
        "Really Closing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) 
        == JOptionPane.YES_OPTION){
                    System.exit(0);
                } else {
                    return;
                }
            }
        }

2 个答案:

答案 0 :(得分:2)

查看Closing an Application

它为此提供了一些基本代码。基本代码会将帧的默认关闭操作设置为DO_NOTHING_ON_CLOSE

然后在WindowListener中,当用户确认关闭时,它会将默认关闭操作重置为EXIT_ON_CLOSE,而不是使用System.exit(0);

你也可以使用CloseListener类,它是一个更复杂的版本(因为它提供了更多功能)你的ExitController类。

答案 1 :(得分:1)

问题出在JFrame.processWindowEvent

protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);  // --> this will call your listener

    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
        switch(defaultCloseOperation) {
          case HIDE_ON_CLOSE:
             setVisible(false);
             break;
          case DISPOSE_ON_CLOSE:
             dispose();
             break;
          case DO_NOTHING_ON_CLOSE:
             default:
             break;
          case EXIT_ON_CLOSE:
              // This needs to match the checkExit call in
              // setDefaultCloseOperation
            System.exit(0);
            break;
        }
    }
}

除了您的听众所做的事情外,JFrame会评估其defaultCloseOperation并关闭或隐藏自己。

因此,您还需要初始化安装侦听器的帧的正确默认关闭操作,以防止默认操作:

frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new ExitController ());

您可以在ExitListener中提供一种方法来促进这一点:

public class ExitController extends WindowAdapter {
     public void installOn(JFrame frame) {
         frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
         frame.addWindowListener(this);
     }
相关问题