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...i.o.w 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.