客户端类:
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/