Java Swing 阻止窗口关闭
Java Swing 的窗口中,使用addWindowListener()添加窗口事件监听器,仅仅是得到窗口事件的通知,并不能阻止窗口的动作(如隐藏),要想阻止窗口的默认动作,可以使用如下方式:
?
public class AFrame extends JFrame{ public AFrame() { this.setSize(400, 300); this.setVisible(true); addWindowListener(new WindowAdapter() { private int oldValue; // 记忆原默认值 public void windowClosing(WindowEvent evt) { if (notClose) { // 不能关闭时 if (getDefaultCloseOperation() != 0) { oldValue = getDefaultCloseOperation(); setDefaultCloseOperation(0); } // 提示不能关闭 } else { // 恢复默认动作 if (oldValue != 0 && getDefaultCloseOperation() == 0) setDefaultCloseOperation(oldValue); } } }); } public static void main(String[] args) { new AFrame(); }}