带有WindowStateListener的JDialog

时间:2011-08-19 22:09:35

标签: java jdialog windowlistener

我正在尝试捕获用户点击事件和JDialog的“X”按钮,并且仅在用户确认时才关闭。所以这是我正在做的骨架:

    public class MyDialog extends JDialog {
      public MyDialog(){
        super();
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        .........   
      }
      .........
    }

   public class Waiter implements WindowStateListener{
@Override
public void windowStateChanged(WindowEvent event) {
    System.out.println(event);
    if (event.getNewState() == WindowEvent.WINDOW_CLOSING) {
        if (shouldClose()) {
            dialog.close();
        }
    }
}
   }

   MyDialog dialog = new MyDialog();
   Waiter waiter = new Waiter();
   dialog.addWindowStateListener(waiter);

正如你猜测的那样,当我点击对话框的“X”时,由于方法从未被调用,因此我没有打印消息。我不确定问题出在哪里。

1 个答案:

答案 0 :(得分:3)

您想使用WindowListener代替WindowStateListener 试试这个:

MyDialog dialog = new MyDialog();        
dialog.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(final WindowEvent event) {
        System.out.println(event);
        if (shouldClose()) {
            dialog.close();
        }
    }
});