Java:如何取消应用程序退出

发布于 2025-01-04 10:02:24 字数 3542 浏览 4 评论 0原文

在我的一个程序中,我希望当用户尝试退出应用程序时出现一个对话框。然后用户必须选择保存程序的某些状态,而不是保存或取消退出操作。

我写这篇文章是为了尝试先找到解决方案,然后再实现它:

import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;

class WL implements WindowListener
{
    private boolean statussaved;
    private JFrame tframe;

    WL (JFrame frame)
    {
        statussaved = false;
        tframe = frame;
    }

    @Override public void windowActivated (WindowEvent w) { }
    @Override public void windowClosed (WindowEvent w) { }
    @Override public void windowDeactivated (WindowEvent w) { }
    @Override public void windowDeiconified (WindowEvent w) { }
    @Override public void windowIconified (WindowEvent w) { }
    @Override public void windowOpened (WindowEvent w) { }

    @Override public void windowClosing (WindowEvent w)
    {
        if (statussaved)
        {
            return;
        }

        final JDialog diag = new JDialog (tframe, "Save Progress", true);
        diag.setPreferredSize (new Dimension (500, 100));
        diag.setResizable (false);
        diag.setDefaultCloseOperation (JDialog.DISPOSE_ON_CLOSE);

        JPanel notifypanel = new JPanel ();
        notifypanel.add (new JLabel ("Do you want to save the current status ?"));

        JButton yesbutton = new JButton ("Yes");
        JButton nobutton = new JButton ("No");
        JButton cancelbutton = new JButton ("Cancel");

        yesbutton.addActionListener (new ActionListener ()
        {
            @Override public void actionPerformed (ActionEvent a)
            {
                //SAVE THE STATUS

                System.out.println ("Saving status...");
                statussaved = true;

                diag.dispose ();
                tframe.dispose ();
            }
        });

        nobutton.addActionListener (new ActionListener ()
        {
            @Override public void actionPerformed (ActionEvent a)
            {
                //just exit/close the application

                diag.dispose ();
                tframe.dispose ();
            }
        });

        cancelbutton.addActionListener (new ActionListener ()
        {
            @Override public void actionPerformed (ActionEvent a)
            {
                //DON'T EXIT !!!

                diag.dispose ();
            }
        });

        notifypanel.add (yesbutton);
        notifypanel.add (nobutton);
        notifypanel.add (cancelbutton);

        diag.setContentPane (notifypanel);

        diag.pack ();
        diag.setVisible (true);
    }
}

public class SaveTest
{
    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable ()
        {
            @Override public void run ()
            {
                JFrame frame = new JFrame ("Save Test");
                frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
                frame.addWindowListener (new WL (frame));

                JLabel lab = new JLabel ("just some information");

                frame.setPreferredSize (new Dimension (400, 300));
                frame.setResizable (false);
                frame.add (lab);
                frame.pack ();
                frame.setVisible (true);
            }
        });
    }
}

它编译并运行时没有任何更改,因此您可以测试它。

“是”和“否”选项按预期工作,但我完全不知道在“取消”按钮的 ActionListener 中写什么。我想要的是,当用户单击“取消”按钮时,对话框消失,但主窗口仍然可见(即程序继续运行)。

现在,由于所有这些都是在 windowClosing 方法中实现的,因此很明显,发送了某种处理信号以销毁 JFrame。这意味着在当前的设计中可能无法做到这一点。我不介意重新组织/重新设计这一切以使其发挥作用。只是……我不知道怎么办。

有什么想法吗?

On one of my programs, I want a Dialog to appear when the user attempts to exit the application. The user must then choose to save some state of the program, not to save or to cancel the exit operation.

I wrote this in an attempt to find a solution first and ony then implement it:

import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;

class WL implements WindowListener
{
    private boolean statussaved;
    private JFrame tframe;

    WL (JFrame frame)
    {
        statussaved = false;
        tframe = frame;
    }

    @Override public void windowActivated (WindowEvent w) { }
    @Override public void windowClosed (WindowEvent w) { }
    @Override public void windowDeactivated (WindowEvent w) { }
    @Override public void windowDeiconified (WindowEvent w) { }
    @Override public void windowIconified (WindowEvent w) { }
    @Override public void windowOpened (WindowEvent w) { }

    @Override public void windowClosing (WindowEvent w)
    {
        if (statussaved)
        {
            return;
        }

        final JDialog diag = new JDialog (tframe, "Save Progress", true);
        diag.setPreferredSize (new Dimension (500, 100));
        diag.setResizable (false);
        diag.setDefaultCloseOperation (JDialog.DISPOSE_ON_CLOSE);

        JPanel notifypanel = new JPanel ();
        notifypanel.add (new JLabel ("Do you want to save the current status ?"));

        JButton yesbutton = new JButton ("Yes");
        JButton nobutton = new JButton ("No");
        JButton cancelbutton = new JButton ("Cancel");

        yesbutton.addActionListener (new ActionListener ()
        {
            @Override public void actionPerformed (ActionEvent a)
            {
                //SAVE THE STATUS

                System.out.println ("Saving status...");
                statussaved = true;

                diag.dispose ();
                tframe.dispose ();
            }
        });

        nobutton.addActionListener (new ActionListener ()
        {
            @Override public void actionPerformed (ActionEvent a)
            {
                //just exit/close the application

                diag.dispose ();
                tframe.dispose ();
            }
        });

        cancelbutton.addActionListener (new ActionListener ()
        {
            @Override public void actionPerformed (ActionEvent a)
            {
                //DON'T EXIT !!!

                diag.dispose ();
            }
        });

        notifypanel.add (yesbutton);
        notifypanel.add (nobutton);
        notifypanel.add (cancelbutton);

        diag.setContentPane (notifypanel);

        diag.pack ();
        diag.setVisible (true);
    }
}

public class SaveTest
{
    public static void main (String[] args)
    {
        SwingUtilities.invokeLater (new Runnable ()
        {
            @Override public void run ()
            {
                JFrame frame = new JFrame ("Save Test");
                frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
                frame.addWindowListener (new WL (frame));

                JLabel lab = new JLabel ("just some information");

                frame.setPreferredSize (new Dimension (400, 300));
                frame.setResizable (false);
                frame.add (lab);
                frame.pack ();
                frame.setVisible (true);
            }
        });
    }
}

It compiles and runs without any change, so you can test it.

The "Yes" and "No" choices work as expected, but I have absolutely no idea what to write in the ActionListener of the "Cancel" button. What I want is, when the user clicks the "Cancel" button, the dialog dissapears, but the main window remains visible (i.e. the program keeps running).

Now, since all this is implemented in the windowClosing method, it's kind of clear that some sort of dispose signal was sent in order to destroy the JFrame. This means that there is probably no way this can be done in the current design. I don't mind reorganizing/redesigning all this to make it work. It's just... I don't know how.

Any ideas ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

筑梦 2025-01-11 10:02:24

替换

mainframe.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

mainframe.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);

如果用户取消关闭 - 不执行任何操作。如果同意 - 手动调用 dispose()

Replace

mainframe.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);

with

mainframe.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);

If user cancels closing - do nothing. If agrees - call dispose() manually.

像极了他 2025-01-11 10:02:24

看一下JOptionPane,它处理大多数为您提供这些东西,例如

JOptionPane.showConfirmDialog(frame, "please choose one", 
      "information",      
      OptionPane.YES_NO_CANCEL_OPTION, 
      JOptionPane.INFORMATION_MESSAGE);

您的 DefaultCloseOperation 需要是 DO_NOTHING_ON_CLOSE 以便您的对话框可以处理事情 - 否则窗口将在用户之前被处理可以取消它。然后您根据用户的选择手动关闭窗口或退出应用程序或其他任何操作。

Have a look at JOptionPane, which handles most of this stuff for you, e.g.

JOptionPane.showConfirmDialog(frame, "please choose one", 
      "information",      
      OptionPane.YES_NO_CANCEL_OPTION, 
      JOptionPane.INFORMATION_MESSAGE);

Your DefaultCloseOperation needs to be DO_NOTHING_ON_CLOSE so that your dialog can handle things - otherwise the window will get disposed before the user can cancel it. Then you manually close the window or exit the application or whatever according to the user's choice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文