eclipse 关于标准 JOptionPane 上的取消按钮的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2324297/
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-09-19 14:26:49  来源:igfitidea点击:

Question about the cancel button on a standard JOptionPane

javaeclipsedoublejoptionpane

提问by Steve

So I am working on a program for school, and part of the assignment is to have a bunch of prompts for input pop up. I am using the JOptionPane, which inherently has an OK button and a Cancel button. Now, to make the program exit when they press cancel when the prompt is asking for a string, I have something like this:

所以我正在为学校开发一个程序,其中一部分任务是弹出一堆输入提示。我正在使用 JOptionPane,它本身就有一个确定按钮和一个取消按钮。现在,为了让程序在提示要求输入字符串时按取消键退出,我有这样的事情:

firstName = JOptionPane.showInputDialog("Please enter your first name:");
if(firstName == null)System.exit(0);

But I also have to do the same thing for numbers I get as input, both Doubles and Ints. If I try the same thing, it throws an error saying The operator == is undefined for the argument type(s) double, null. So, what is the best way for me to check if they click Cancel when being prompted for a numerical value? Thanks for your help!

但我也必须对作为输入的数字做同样的事情,双打和整数。如果我尝试同样的事情,它会抛出一个错误,说运算符 == 未定义参数类型 double, null。那么,当我被提示输入数值时,检查他们是否单击取消的最佳方法是什么?谢谢你的帮助!

Edit #1

编辑 #1

Here is the code for the JOptionPane getting a numerical value:

这是 JOptionPane 获取数值的代码:

startDateMonth = Integer.parseInt(JOptionPane.showInputDialog("Please enter the start         date month (1-12):"));

回答by Petar Minchev

JOptionPane.showInputDialog() returns always a string which is the user input. If the user has clicked the Cancel button it will return null. If you want to convert the user input to another type just parse the string. I mean the code you have pasted should remain the same. If you are asking for a different thing, please clarify.

JOptionPane.showInputDialog() 总是返回一个字符串,它是用户输入。如果用户单击了取消按钮,它将返回 null。如果要将用户输入转换为另一种类型,只需解析字符串。我的意思是你粘贴的代码应该保持不变。如果您要求不同的东西,请澄清。

Petar

佩塔尔