Press the cancel button showInputDialogue

I have a question about pressing the cancel button of my Dialoguebox input. I asked a similar question before I apologize if I seem to be repeating myself.

The main problem that I am facing is that my code runs regardless of what I click cancel, and the socket connection is obtained even if I do not add any input.

Why is this happening 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); 

Thus, the code will be the same as when the client is connected, even if I click cancel. Is this the reason, perhaps because I have the Server and Client as two separate programs on the same machine? How can i avoid this?

+7
source share
2 answers

When you click Cancel Button showInputDialog(...) , you always get a zero value for which the condition is not met, so a new connection is always established. Therefore, you can add this condition as follows:

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

It will always remain in a different state, even if the cancel button is pressed. Check

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

add a code higher than the previous one and press the cancel button.

+2
source

All Articles