WindowListener not working as I override the function

282 Views Asked by At

I'm writing a GUI. I want to print something after I close. But the WindowListener does not work. I write a window then I want to have a boolean to mark the windows is closed. So after I can use that boolean in if clause to write the next statement which should be executed after windows close.

public class MyFrame extends JFrame implements  WindowListener {

    private boolean close=false;

    MyFrame() {
        this.close=false;
        setSize(300,250);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        addWindowListener(this);
           // after help, I've added addWindowListener although still don't 
            //work

    }

    public void windowOpened()/windowIconified()/windowDeiconified()...
    public void windowClosing(WindowEvent e) {close=true;}
    public void windowClosed(WindowEvent e) {close=true;}
}

public class MyFrameControl {
    MyFrame setframe() {
        MyFrame fr = new MyFrame();
        fr.setVisible(true);
        return fr;
    }
}

public class test {
    public static void main(String args[]) {
        MyFrameControl frameCtrl= new MyFrameControl();
        MyFrame tmpFrame = frameCtrl.setframe(); 

        if(tmpFrame.close==true) {
            System.out.println("close is true");
        }
    }
}

When I close the JFrame/MyFrame, isn't the boolean close supposed to be true when the print line is executed? Still can't work under JFrame after adding addWindowListener, is there any solution under JFrame other than switching to JDialogue?

1

There are 1 best solutions below

0
SirFartALot On

No.

Your code is not waiting for the JFrame to be closed again and like @Abra already mentioned, you never add the WindowListener to the JFrame.

Your k.setVisible(true) returns immediately and your frame remains visible.

So no windowClosing()/windowClosed() is called at the time the condition is checked.

Maybe you could transform your JFrame to a JDialog which can be set to modal (setModal()/setModalityType()). A modal dialog's setVisible() returns after the dialog has been closed.

To simulate this with a JFrame you have somehow to wait for the close to occur. You could put your System.out... in a thread (Runnable) which waits until close==true.

A JFrame is not modal by definition (How to make a JFrame Modal in Swing java)