Java中的输入对话框

时间:2012-03-14 09:56:28

标签: java swing sockets joptionpane

我忙于学校的项目,我使用InputDialogbox从用户那里获取主机名,以便建立客户端套接字。

有两件事让我感到困惑。

首先,我建立一个连接服务器端,然后我建立客户端连接如下。

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

如果我在对话框中按Enter而不进行任何输入... i.o.w没有指定IPAddress,无论如何都要连接到套接字,这让我感到困惑。那是为什么?

为了克服这个“问题”,我决定让用户在对话框中输入一个条目

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

问题是,如果我点击取消,我会得到一个NullPointerException。 如何在不收到此异常的情况下取消“对话”框?

亲切的问候 阿里安

4 个答案:

答案 0 :(得分:4)

只是做:

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 ...

您不必抛出异常,只需在输入错误时跳过套接字创建。您也可以在注意到用户的位置创建一个else分支。

答案 1 :(得分:3)

将条件更改为if(input!=null && input.equals("")) ...如果您在“输入”对话框中按取消,则input将为空。当您致电NullPointerException时,这会抛出input.equals("")。所以只需在你的条件之前添加一个空检查......

答案 2 :(得分:2)

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

答案 3 :(得分:1)

简单的解决方案是:

if(input != null && input.equals(""))
相关问题