关于java JFrame窗口关闭弹出showConfirmDialog 对话框关闭而主窗口不关闭

来源:百度知道 编辑:UC知道 时间:2024/06/19 22:55:56
我在做一个java 记事本小程序 中间遇到了问题:就是我关闭JFrame主窗口的小红叉时 想弹出对话框时头要保存,具体如下
this.addWindowListener(new WindowAdapter() { //窗口关闭事件监听与实现
public void windowClosing(WindowEvent evt) {
jta.requestFocus();
String currentValue = jta.getText();
boolean isTextChange = (currentValue.equals(oldValue)) ? false : true;
if (isTextChange) {
int saveChoose = JOptionPane.showConfirmDialog(jf, "您的文件尚未保存。是否保存?", "提示", JOptionPane.YES_NO_CANCEL_OPTION);
if (saveChoose == JOptionPane.YES_OPTION){
JFileChooser j =new JFileChooser();
int select =j.showSaveDialog(jf);
if(select==JFileChooser.APPROVE_OPTION){
File file =j.getSelectedFile();
try{
FileOutputStream fout =new FileOutputStream(file);
OutputStreamWriter out =new OutputStreamWriter(fout);
jta.write(out);
out.close();
}catch(FileNotFoundException fe){}
catch(EOF

JFrame窗口的小红叉默认就是点击就关闭,所以无论你选择什么它都会关闭,只要在你的构造函数里添加一句话就能实现你想要的功能,其它代码不用动,即使要有小的改动,我想你自己也能搞定。

把这句话加在你的构造函数里就可以了,试试看。
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);