按下 x 按钮时如何关闭 JOptionPane 消息框?

How to close a JOptionPane message box when pressing the x button?

我使用 JOptionPane showMessageDiaglog 来显示带有选项的消息,但每当我决定后退并单击红色 X 按钮时。它仍然执行一个动作,就好像我按下了第一个选项一样。我如何让它在退出时关闭?

我是这样写的:

int n = JOptionPane.showOptionDialog(g, "?", "Check", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, l, l[0]);

很简单

//First of all put the options dialog code like this.
int n = JOptionPane.showOptionDialog(this, "?", "Check", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null,null,null);
//Now grab the value of n into switch case like this.
switch(n)
{
    case 0:
        //Yes
    break;
    case 1:
        //No
    break;
    case 2:
        //Cancel
    break;
    case -1:
        //User pressed 'X' button on the options dialog.If you want to exit app here.
        System.exit(0);
    break;
}

这里有一个提示。

如果您想检查任何消息对话框的 return 值,只需获取 return 值并将其打印在控制台上,或者只显示另一个带有 return 中的值 it.So 你可以很容易地理解,当用户在消息对话框中按下什么按钮时会发生什么。

希望这能解决您的问题。