如何捕获 JFrame 的关闭按钮单击事件? [英] How to capture a JFrame's close button click event?

查看:46
本文介绍了如何捕获 JFrame 的关闭按钮单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当JFrame标题栏的红色关闭按钮被点击时,我想调用一个方法confirmExit().

I want to call a method confirmExit() when the red close button of the title bar of a JFrame is clicked.

如何捕获该事件?

如果用户选择不继续,我还想阻止窗口关闭.

I'd also like to prevent the window from closing if the user chooses not to proceed.

推荐答案

import javax.swing.JOptionPane;
import javax.swing.JFrame;

/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
        if (JOptionPane.showConfirmDialog(frame, 
            "Are you sure you want to close this window?", "Close Window?", 
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
            System.exit(0);
        }
    }
});

如果您还想阻止窗口关闭,除非用户选择是",您可以添加:

If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

这篇关于如何捕获 JFrame 的关闭按钮单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆