Java聊天程序: Client Class not working due to null pointer exception

标签 java nullpointerexception

客户端类:

public void connect(String user){
            try{
                host = socket.getInetAddress();
                socket = new Socket(host,port);

            }

        }

登录类:

login.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {

                String user = textInput.getText();
                Client client = new Client(username, 7777);
                client.setVisible(true);
                try{
                  client.connect(username);
                }
                catch(NullPointerException e){
                  e.printStackTrace();
                }
        }

    });

我从 Client 类调用连接,并 try catch NullPointerException 但仍然收到错误。我还尝试插入 null 检查 而不是 try 和 catch 子句 我试图环顾四周,但没有找到任何答案。有人可以告诉我出了什么问题吗?我想要的是客户端能够成功连接。

最佳答案

最初,似乎有一个局部变量声明。评论表明这可能是不正确的。因此,问题在于 Client 类实例化了一个对象,但 Login 类未获取对该对象的引用。

EDIT2:经过额外讨论,似乎尽管有一个 main 方法,但实际的启动类是 Login 类,而不是 Client 类。因此,client 对象未实例化。

将实例化移至 Login 类解决了 NPE。

public class Login {
  //declare and instantiate a Client object
  static Client client = new Client();
 ....

  loginB.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent e) {

            String username = usernameTF.getText();
            ClientGUI clientgui = new ClientGUI(username, 7777);
            clientgui.setVisible(true);
            try{
              // get the instantiated client
              System.out.println("Attempting connection for " + username +  
                "(client == null): " + (client == null ? "true" : "false"));

              // use the static variable
              client.connectClient(username);
            }
            catch(NullPointerException npe){
              npe.printStackTrace();
            }
    }

});
}

关于Java聊天程序: Client Class not working due to null pointer exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750682/

相关文章:

java - Maven:使用响应 Java EE 部署 HTML 表单页面,并使用 POST 打印结果

java - 使用java添加多个数字

java - 定时器任务和线程

java - 使用 GWT 读取一个非常大的本地 XML 文件

android - 一段时间不活动后应用程序响应异常

android - java.lang.NullPointerException : Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource (int)' on a null object reference 异常

java - try catch block 中的空指针异常

对代码进行必要的更改时出现 java.lang.NullPointerException(Java Netbeans IDE 7.4 和 JDK 1.7)

java - Spring Test模拟一个依赖

java - 添加多种用户类型,每个用户都有不同的功能