Search code examples
javajdialogwindowlistener

JDialog with WindowStateListener


I am trying to catch an event of user clicking on and "X" button of a JDialog and only close if a user confirms. So here is skeleton of what I am doing:

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

As you can guess, when I click on "X" for the dialog, I do not get a message printed becasue the methodis never called. I am not sure where is the problem.


Solution

  • You want to use a WindowListener instead of a WindowStateListener.
    Try this:

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