次のように、テストコードで「windowClosed」メソッドが呼び出されないという問題があります。
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);
}
}
ステートメント setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) を記述するか、dispose() を明示的に TFrame に呼び出すと、windowClosed() が呼び出されます。
誰かがそれをより詳細に説明できますか?
////////////////// ダンのガイドに従って更新 //////////////
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);
}
}