这是我的班级
public class MessageFrameListener{
private MessageFrame mf;
private User us;
private Contact cn;
private Socket s;
private PrintStream ps;
private BufferedReader br;
public MessageFrameListener(MessageFrame m_f, User u_s, Contact c_n){
mf = m_f;
us = u_s;
cn = c_n;
m_f.addButtonListener(new SButtonListener());
}
public void init(){
try {
s = new Socket(InetAddress.getLocalHost(), 8072);
PrintStream ps = new PrintStream(s.getOutputStream());
BufferedReader br = new BufferedReader( new InputStreamReader(s.getInputStream()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class SButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String insert = mf.getInput();
String infoString = "m "+us.getName()+" "+cn.getName()+" "+insert;
ps.println(infoString);
mf.addLine(insert);
mf.refreshInput();
}
}
我在这一行得到NullPointerException
ps.println(infoString);
旧版本,就像这样,可以工作(我在方法中初始化套接字)
public class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
try{
Socket s = new Socket(InetAddress.getLocalHost(), 8072);
PrintStream ps = new PrintStream(s.getOutputStream());
BufferedReader br = new BufferedReader( new InputStreamReader(s.getInputStream()));
String infoString = "add "+us.getName()+" "+af.getName();
ps.println(infoString);
String result = br.readLine();
s.close();
} catch (UnknownHostException ex) {
System.out.println("адрес недоступен");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("ошибка I/О потока");
ex.printStackTrace();
}
}
答案 0 :(得分:6)
该行
PrintStream ps = new PrintStream(s.getOutputStream());
创建一个隐藏ps
的局部变量this.ps
。将其更改为
ps = new PrintStream(s.getOutputStream());
以初始化ps
成员变量。