Java 单击取消按钮 showInputDialogue
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9733702/
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
Clicking the cancel button showInputDialogue
提问by Arianule
I have a question in regards to pressing the cancel button of my inputDialoguebox. I have asked a similar question before so I apologize if I seem to repeat myself.
我有一个关于按下 inputDialoguebox 的取消按钮的问题。我之前也问过类似的问题,所以如果我似乎重复自己的话,我深表歉意。
The main problem I have is that my code executes regardless of me pressing cancel and a socket connection does get made even if I don't add any input.
我遇到的主要问题是,无论我按下取消键,我的代码都会执行,并且即使我不添加任何输入,也会建立套接字连接。
Why does this happen and how can I avoid this?
为什么会发生这种情况,我该如何避免这种情况?
String input = "";
try
{
InetAddress host = InetAddress.getLocalHost();
String hostAddress = host.getHostAddress();
//setting label to host number so as to know what number to use
labHostName.setText("(" + hostAddress + ")");
input = JOptionPane.showInputDialog(null,"Please enter host name to access server(dotted number only)...see number on frame", "name", JOptionPane.INFORMATION_MESSAGE);
if(input != null && "".equals(input))//input != null && input.equals(""))
{
throw new EmptyFieldsException();
}
else if(input != null && !input.equals(hostAddress))
{
throw new HostAddressException();
}
else
{
clientSocket = new Socket(input, 7777);
So with the code being the way it is at the moment the clientsocket connection is made even if I do press cancel. Is the reason for this perhaps because I have the Server and Client as two seperate programs on the same machine? How can I avoid this from happening?
因此,即使我按下取消键,代码也是此时建立客户端套接字连接的方式。这样做的原因可能是因为我在同一台机器上将服务器和客户端作为两个单独的程序?我怎样才能避免这种情况发生?
采纳答案by nIcE cOw
When you click on the Cancel Button
of the showInputDialog(...)
, you always get a null value, for which no condition is satisfied, hence a new connection is always established.
So you can add this condition like this :
当你点击 的Cancel Button
时showInputDialog(...)
,你总是得到一个空值,没有满足任何条件,因此总是建立一个新的连接。所以你可以像这样添加这个条件:
if(input == null || (input != null && ("".equals(input))))
{
throw new EmptyFieldsException();
}
回答by Rahul Borkar
It will always go in else condition even if cancel button is pressed. Check for,
即使按下取消按钮,它也将始终处于 else 状态。检查,
else if(input == JOptionPane.CANCEL_OPTION){
System.out.println("Cancel is pressed");
}
add above code before last else statement explicitly, and handle cancel button pressed there.
在最后一个 else 语句之前显式添加上面的代码,并处理在那里按下的取消按钮。
回答by Ahmed Ktob
I had this same issue, and I solved it as follow:
我有同样的问题,我解决了如下:
if(input != null){
if(!input.isEmpty()){
// Do whatever...
}
}
So, I basically moved the nulltest before testing if the user has entered some input. Hope this helped!
所以,在测试用户是否输入了一些输入之前,我基本上移动了空测试。希望这有帮助!