java 文本对话框,点击了哪个按钮?

java text dialog, which button was clicked?

我遵循了 java 对话框的官方指南,所以我得到了这个代码:

String s = JOptionPane.showInputDialog(this, "Text\n\nEnter your name", "Heading", JOptionPane.PLAIN_MESSAGE);

如何检查用户是否单击了“确定”或“取消”按钮?

试试这个:

String input = JOptionPane.showInputDialog(this, "Text\n\nEnter your name", "Heading", JOptionPane.PLAIN_MESSAGE);
if (input!=null) { ....}

请注意,当用户点击 "cancel" 时,input 将为 null

所以如果你想检查用户是否点击了取消或确定按钮,你可以这样尝试

String input = JOptionPane.showInputDialog(this, "Text\n\nEnter your name", "Heading", JOptionPane.PLAIN_MESSAGE);
if (input != null) { 
 // functionality for the OK button click
} else {
 // functionality for the Cancel button click
}

showInputDialog:

Returns:
user's input, or null meaning the user canceled the input

如果方法调用 returns null,则用户按下 取消 。否则,如果他按下 ok,它将包含用户输入。