I have an issue that why "windowClosed" method not being invoked in my test code as following,
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Tmp {
class TFrame extends JFrame{
private static final long serialVersionUID = -5729542298504858399L;
public TFrame() {
setTitle("title");
setSize(300, 300);
}
}
public static void main(String[] args) {
final TFrame t = new Tmp().new TFrame();
t.addWindowStateListener(new WindowAdapter() {
@Override
public void windowStateChanged(WindowEvent e) {
super.windowStateChanged(e);
System.out.println(e.getOldState() + "<-old new->" + e.getNewState());
}
});
t.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
System.out.println(e.getID() + "closed " + e.getNewState());
}
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.out.println(e.getID() + "closing" + e.getNewState());
}
});
t.setVisible(true);
}
}
If I write the statement setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) or explicitly call dispose() to TFrame, windowClosed() will get called.
Is there anyone can explain it in more detail, I'm confusing what is the property way of writing listeners for windowClosed(), thanks in advance.
////////////////// updated according to some guides from Dan //////////////
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Tmp {
class TFrame extends JFrame {
// ignored .....
t.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
super.windowClosed(e);
System.out.println(e.getID() + "closed " + e.getNewState());
}
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.out.println(e.getID() + "closing" + e.getNewState());
int quit = JOptionPane.showConfirmDialog(t, "Are you sure to quit?");
if(quit == JOptionPane.YES_OPTION){
t.dispose();
}
else if (quit == JOptionPane.NO_OPTION){
t.setVisible(false);
}
}
});
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
The default value for setDefaultCloseOperation
is HIDE_ON_CLOSE
. With this, the window is not closed, it is only hidden.
Changing the value to something else, you get it to actually close rather than just hide it, so the event will be triggered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With