[英]Java Chat Program: Client Class not working due to null pointer exception
Client class: 客户类:
public void connect(String user){
try{
host = socket.getInetAddress();
socket = new Socket(host,port);
}
}
The Login class: 登录类:
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();
}
}
});
I'm calling the connect from the Client
class and I tried catching the NullPointerException
but I still get the error. 我正在从
Client
类调用connect,我尝试捕获NullPointerException
但我仍然得到错误。 I also tried inserting a null check
instead of the try and catch clause
I've tried to look around but I haven't found any answers. 我也尝试插入一个
null check
而不是我试图环顾四周但我没有找到任何答案的try and catch clause
。 Can somebody tell me whats wrong please? 有人能告诉我什么错了吗? What I want is the client to successfully connect.
我想要的是客户端成功连接。
您可以确保在调用connectClient()之前启动clientSocket。
Originally, it appeared there was a local variable declaration. 最初,似乎有一个局部变量声明。 Comments indicate perhaps that was incorrect.
评论表明这可能是错误的。 The issue is therefore that the
Client
class instantiated an object, but the Login
class did not obtain a reference to it. 因此问题是
Client
类实例化了一个对象,但是Login
类没有获得对它的引用。
EDIT2 : after additional discussion, it appears that despite having a main
method, the actual startup class was the Login
class, rather than the Client
class. EDIT2 :经过额外讨论后,看起来尽管有一个
main
方法,但实际的启动类是Login
类,而不是Client
类。 As a result, the client
object was not instantiated. 结果,
client
对象未实例化。
Moving the instantiation to the Login
class resolved the NPE. 将实例化移动到
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();
}
}
});
}
You have to change your connectClient method 您必须更改您的connectClient方法
public void connectClient(String user){
try{
//clientSocket is not instantiated yet
host = InetAddress.getByName("127.0.0.1");
clientSocket = new Socket(host,port);
String connected = user+" just connected";
clientGUI.appendMessage(accepted+"\n"+connected);
serverGUI.appendEventsLog(accepted+"\n"+connected);
new ClientHandler().run();
}
catch(Exception e){
sendMessage("Connection error: "+e);
serverGUI.appendEventsLog("Client "+new ClientGUI(username, port)+" failed to connect");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.