2012-05-14 82 views
0

這裏是我插座+的readline =空指針異常

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

舊的版本,這樣,作品(在這裏我initalize裏面方法插座)

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


    } 

回答

6

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

創建了一個局部變量ps,它隱藏了this.ps。它更改爲

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

爲了初始化ps成員變量。