单击取消按钮showInputDialogue

我有一个关于按下inputDialoguebox的取消按钮的问题。 我之前已经问过类似的问题,所以如果我好像重复自己,我会道歉。

我遇到的主要问题是我的代码执行无论我是否按下取消,即使我没有添加任何输入,也会进行套接字连接。

为什么会发生这种情况,我该如何避免这种情况?

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); 

因此,即使我按下取消,代码就是目前正在进行clientocket连接的方式。 这可能是因为我在同一台机器上将服务器和客户端作为两个单独的程序? 我怎样才能避免这种情况发生?

单击showInputDialog(...)的“ Cancel Button时,总是会得到一个空值,对于该值,不满足条件,因此始终建立新连接。 所以你可以添加这样的条件:

 if(input == null || (input != null && ("".equals(input)))) { throw new EmptyFieldsException(); } 

即使按下取消按钮,它也将始终处于其他状态。 检查,

 else if(input == JOptionPane.CANCEL_OPTION){ System.out.println("Cancel is pressed"); } 

在显式的last else语句之前添加上面的代码,并在那里处理按下取消按钮。

我有同样的问题,我解决了以下问题:

 if(input != null){ if(!input.isEmpty()){ // Do whatever... } } 

所以,如果用户输入了一些输入,我在测试之前基本上移动了测试。 希望这有帮助!