单击取消按钮showInputDialogue

Ari*_*ule 8 java sockets joptionpane

我有一个关于按下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);
Run Code Online (Sandbox Code Playgroud)

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

nIc*_*cOw 8

当你点击Cancel ButtonshowInputDialog(...),你总是得到一个空值,对于没有条件满足,因此一个新的连接总是建立.所以你可以添加这样的条件:

if(input == null || (input != null && ("".equals(input))))   
{
    throw new EmptyFieldsException();
}
Run Code Online (Sandbox Code Playgroud)