简体   繁体   中英

The input Dialogue box in Java

I am busy with a project for school where I use the InputDialogbox to get the hostname from the user so as to make a client socket connection.

There are two things that puzzle me a bit.

Firstly I make a connection Server Side and then I make the client connection as follow.

input = JOptionPane.showInputDialog(null, "Please enter host name to access" +
                  "server(dotted number only)...see number on frame", "name",
                   JOptionPane.INFORMATION_MESSAGE); 

clientSocket = new Socket(input, 7777);

what puzzles me as that if I press enter in the Dialogue box without making any entry...iow without specifying the IPAddress the connection to the socket is made regardless. Why is that?

To overcome this 'problem' I decided to try to get the user to make an entry in the dialogue box

if(input.equals(""))
{
    throw new EmptyFieldsException();
}

The thing is that now if I click on cancel I get a NullPointerException. How can I cancel the Dialogue box without getting this exception?

Kind regards Arian

Just do:

input = JOptionPane.showInputDialog(null,"host name", "name", JOptionPane.INFORMATION_MESSAGE); 

if (input != null && input.equals("")) {
    clientSocket = new Socket(input, 7777);
    // Socket created
} else {
    // Else not ...

You don't have to throw an exception, you can just skip the socket creation when the input is bad. You can create an else branch where you notice the user, too.

Change condition to if(input!=null && input.equals("")) ...your input will be null if you press cancel in the Input dialog.This will throw a NullPointerException when you call input.equals("") . So just adding a null check before your condition...

或者只是if("".equals(input))

简单的解决方案是:

if(input != null && input.equals(""))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM