如何检测用户是否通过红叉关闭了 window?

How can I detect if a user closes the window via the red cross?

我的代码的目标是获取用户输入,当用户想要保存数据时,他们按下“确定”选项。但是,如果用户已经输入了一些数据,不想再继续了,那么他们就直接点击右上角的红叉退出按钮,不保存直接退出?

我该怎么做?

这是我的代码:

JOptionPane.showMessageDialog(null, myPanel, "Edit Fruit", JOptionPane.INFORMATION_MESSAGE);

...

if (!(JOptionPane.OK_OPTION))
{
   //If the user exits the option pane via the red cross, exit the loop.
   break;
}

编辑:这段代码不起作用,因为我只是在寻找 JOptionPane.showMessageDialog 何时通过红十字而不是 OK 按钮关闭:

addWindowListener(new WindowAdapter()
    {
        @Override
        public void windowClosing(WindowEvent e)
        {
            System.out.println("Closed");
            e.getWindow().dispose();
        }
    });

即使我在 JOptionPane 中按下“确定”选项,代码仍然会执行。我只想听红叉出口

感谢您的帮助。

首先,仅当用户通过红色 x 关闭 window 而不是通过键入 Alt-F4,或双击图标,或Alt-Space-C,等等;所以我假设你只是想关闭而不是按 OK 按钮,而不是专门按红色 x。

您有代码可以检测 window 何时关闭。

您有代码可以检测用户何时按下 OK 按钮。

所以设置一个标志来指示 OK 按钮被按下,如果在 window 关闭时没有设置标志,则用户在没有按下 OK 按钮的情况下关闭了 window。

另一个使用关键字 "JOptionPanel close listener" 的快速搜索将我带到另一个问题。

How can I add a listener on the ok button of JOptionPane?

接受的答案建议检查方法 showOptionDialog 的 return 值。

But you can use the method JOptionPane.showOptionDialog with a single DEFAULT_OPTION for the OK button. The showOptionDialog will return 0 if OK was clicked and -1 if the user closed the dialog.

int res = JOptionPane.showOptionDialog(null, "Hello", "Test",
JOptionPane.DEFAULT_OPTION,
    JOptionPane.INFORMATION_MESSAGE, null, null, null);

System.out.println(res); 

You don't need a listener because the javadoc says:

Each showXxxDialog method blocks the caller until the user's interaction is complete.

在这里,正如第一个答案所暗示的,close 与 rea cross、组合键等没有区别。但是,我想也许你不需要。