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?
No.
Your code is not waiting for the
JFrameto be closed againand like @Abra already mentioned, you never add the.WindowListenerto theJFrameYour
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
JFrameto aJDialogwhich can be set tomodal(setModal()/setModalityType()). A modal dialog'ssetVisible()returns after the dialog has been closed.To simulate this with a
JFrameyou have somehow to wait for the close to occur. You could put yourSystem.out...in a thread (Runnable) which waits untilclose==true.A
JFrameis not modal by definition (How to make a JFrame Modal in Swing java)