Java 如何在 JOptionPane 的确定按钮上添加侦听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18715650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:25:21  来源:igfitidea点击:

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

javaswingmouseeventjoptionpane

提问by Ankit Lamba

How can I add a listener on the click of "OK" button of JOptionPane.INFORMATION_MESSAGE.

如何在单击“确定”按钮时添加侦听器JOptionPane.INFORMATION_MESSAGE

My JOptionPane is:

我的 JOptionPane 是:

JOptionPane.showMessageDialog(null, "Your password is: " + password, "Your Password", JOptionPane.INFORMATION_MESSAGE);

采纳答案by cyon

The showMessageDialogmethod returns void when the user closes or clicks ok. But you can use the method JOptionPane.showOptionDialogwith a single DEFAULT_OPTIONfor the OK button. The showOptionDialogwill return 0 if OK was clicked and -1 if the user closed the dialog.

showMessageDialog当用户关闭或单击确定时,该方法返回 void。但是您可以使用JOptionPane.showOptionDialog带有单个DEFAULT_OPTIONOK 按钮的方法。showOptionDialog如果单击 OK ,则返回 0,如果用户关闭对话框,则返回 -1。

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 javadocsays:

您不需要侦听器,因为javadoc说:

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

每个 showXxxDialog 方法都会阻塞调用者,直到用户的交互完成。

回答by Vimal Bera

When the button on JOptionPaneis clicked, it returns the index value of button. By checking the value, you can get to know that Okbutton is clicked or not.

当按钮 onJOptionPane被点击时,它返回按钮的索引值。通过检查该值,您可以了解Ok按钮是否被点击。