setDefaultCloseOperation 改为显示 JFrame [英] setDefaultCloseOperation to show a JFrame instead

查看:27
本文介绍了setDefaultCloseOperation 改为显示 JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了练习 Java,我正在制作一个文字处理器应用程序,我希望这样当用户尝试关闭应用程序时,会出现一个 JFrame,要求保存更改.

I am making a word processor application in order to practise Java and I would like it so that when the user attempts to close the appliction, a JFrame will come up asking to save changes.

我正在考虑 setDefaultCloseOperation() 但到目前为止我运气不佳.如果可能的话,我也希望它在用户单击窗口右上角的X"时出现.

I was thinking about setDefaultCloseOperation() but I have had little luck so far. I would also like it to appear whent he user clicks the "X" on the top right of the window aswell if possible.

推荐答案

您可以将 JFrame DefaultCloseOperation 设置为 DO_NOTHING 之类的东西,然后设置一个 WindowsListener 来获取关闭事件并执行您想要的操作.我会在几分钟后发布一个示例.

You can set the JFrame DefaultCloseOperation to something like DO_NOTHING, and then, set a WindowsListener to grab the close event and do what you want. I'll post an exemple in a few minutes .

这是示例:

public static void main(String[] args) {
        final JFrame frame = new JFrame("Test Frame");

        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        frame.setSize(800, 600);

        frame.addWindowListener(new WindowAdapter() {
            //I skipped unused callbacks for readability

            @Override
            public void windowClosing(WindowEvent e) {
                if(JOptionPane.showConfirmDialog(frame, "Are you sure ?") == JOptionPane.OK_OPTION){
                    frame.setVisible(false);
                    frame.dispose();
                }
            }
        });

        frame.setVisible(true);
    }

这篇关于setDefaultCloseOperation 改为显示 JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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