我的代码是这样的
this.setTitle("图书管理系统--" + adminmsg.getAdminName());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
int option = JOptionPane.showConfirmDialog(null,"是否退出","提示",JOptionPane.YES_NO_OPTION);
if(option == 0)
System.exit(0);
else
return;
}
});
不管我点击“是”还是“否”程序都退出求解为什么
this.setTitle("图书管理系统--" + adminmsg.getAdminName());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
int option = JOptionPane.showConfirmDialog(null,"是否退出","提示",JOptionPane.YES_NO_OPTION);
if(option == 0)
System.exit(0);
else
return;
}
});
不管我点击“是”还是“否”程序都退出求解为什么
this.setTitle("图书管理系统--" + adminmsg.getAdminName());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
int option = JOptionPane.showConfirmDialog(null,"是否退出","提示",JOptionPane.YES_NO_OPTION);
if(option == 0)
System.exit(0);
else
;
}
});
那怎么做才能阻止close时间呢
private int defaultCloseOperation = HIDE_ON_CLOSE;
通过这句代码可以看出,JFrame的默认关闭时执行的操作为隐藏窗口。
下面为JFrame处理窗口事件的代码:protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) {
switch(defaultCloseOperation) {
case HIDE_ON_CLOSE:
setVisible(false);
break;
case DISPOSE_ON_CLOSE:
dispose();
break;
case DO_NOTHING_ON_CLOSE:
default:
break;
case EXIT_ON_CLOSE:
// This needs to match the checkExit call in
// setDefaultCloseOperation
System.exit(0);
break;
}
}
}通过上面的代码可以看出JFrame就是根据defaultCloseOperation来决定对窗口的操作的。
因此可以在开始的时候设置defaultCloseOperation为DO_NOTHING_ON_CLOSE。这样当关闭窗口的时候就不执行处理了,然后可以在你加的事件中关闭窗口。
下面的代码,可以实现这个需求:package T;import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;import javax.swing.JFrame;
import javax.swing.JOptionPane;public class Test extends JFrame {
public Test() {
this.setTitle("图书管理系统");
this.setSize(800, 600);
this.setVisible(true);
//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int option = JOptionPane.showConfirmDialog(null, "是否退出", "提示",
JOptionPane.YES_NO_OPTION);
if (option == 0) {
System.exit(0);
}
}
});
}
public static void main(String[] args) {
new Test();
}
}
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
默认情况下是DisposeOnClose,也就是当关闭时就释放所有窗口所占用的资源,如果所有的窗口资源被释放,程序退出按照楼上的改法,你就可以自己处理关闭动作了,Java不会自主做任何事
private int defaultCloseOperation = HIDE_ON_CLOSE;
public void windowClosing(WindowEvent e)
{
int option = JOptionPane.showConfirmDialog(null,"是否退出","提示",JOptionPane.YES_NO_OPTION);
if(option == 0)
//System.exit(0);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
else
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//return;
}
});