0

Here is my class

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

I get NullPointerException at this line

    ps.println(infoString);

The old version, like this , works(where I initalize sockets inside method)

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


    }
4

1 回答 1

6

The line

PrintStream ps = new PrintStream(s.getOutputStream());

creates a local variable ps which hides this.ps. Change it to

ps = new PrintStream(s.getOutputStream());

in order to initialize the ps member variable.

于 2012-05-14T17:48:43.287 回答