java window closed,Java - 如何防止WindowClosing实际关闭窗口

I seem to have the reverse problem to most people. I have the following pretty standard code to see if the user wants to do some saves before closing the window:

frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent ev) {

boolean close = true;

// check some files, asking if the user wants to save

// YES and NO handle OK, but if the user hits Cancel on any file,

// I want to abort the close process

// So if any of them hit Cancel, I set "close" to false

if (close) {

frame.dispose();

System.exit(0);

}

}

});

No matter what I try, the window always closes when I come out of windowClosing. Changing WindowAdapter to WindowListener doesn't make any difference. What is weird is that the documentation explicitly says "If the program does not explicitly hide or dispose the window while processing this event, the window close operation will be cancelled," but it doesn't work that way for me. Is there some other way of handling the x on the frame? TIA

解决方案

I've just tried this minimal test case:

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import javax.swing.WindowConstants;

public class test {

public static void main(String[] args) {

final JFrame frame = new JFrame("Test");

frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent ev) {

//frame.dispose();

}

});

frame.setVisible(true);

}

}

If I keep the dispose call commented, and hit the close button, the window doesn't exit. Uncomment that and hit the close button, window closes.

I'd have to guess that something is wrong in your logic to set your "close" variable. Try double checking that.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值