chatclient中的java.lang.NullPointerException

时间:2014-08-11 11:12:33

标签: java

我是Java的新手,我正在创建一个可以发送和接收文本的聊天客户端。但我被困在这里:

exception-at Netr$IncomingReader.run(Netr.java:88) at java.lang.Thread.run(Thread.java:745) java.lang.NullPointerException

应用程序在执行时以java.lang.NullPointerException终止。请帮忙。提前谢谢。

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
public class Netr {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
JScrollPane qscroller;
public static void main(String[]args)
{
Netr ab=new Netr();
ab.go();
}
public void go()
{
JFrame frame=new JFrame("my first client baby");
JPanel panel=new JPanel();
incoming=new JTextArea();
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
qscroller=new JScrollPane(incoming);
qscroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qscroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing=new JTextField(20);
JButton sendbutton=new JButton("Send");
sendbutton.addActionListener(new SendButtonListener());
panel.add(qscroller);
panel.add(sendbutton);
panel.add(outgoing);
setupnetworking();
IncomingReader thef=new IncomingReader();
Thread abc=new Thread(thef);
abc.start();
frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.setSize(400,500);
frame.setVisible(true);}


private void setupnetworking()
{
try
{
    ServerSocket serversock=new ServerSocket(3311);
    sock =new Socket("100.68.56.116",3311);
    Socket sock1=serversock.accept();
    InputStreamReader reader=new InputStreamReader(sock.getInputStream());
    BufferedReader streamreader=new BufferedReader(reader);
    writer=new PrintWriter(sock.getOutputStream());
    System.out.println("newtorking established");
}
catch(IOException ex)
{
    ex.printStackTrace();
}
}
public class SendButtonListener implements ActionListener
{public void actionPerformed(ActionEvent ev)
{
try
{
    writer.println(outgoing.getText());
    writer.flush();
}
catch(Exception ex)
{
    ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public class IncomingReader implements Runnable
{
private BufferedReader streamreader;

public void run()
{
    String message;
    try
    {
        while((message= streamreader.readLine())!=null)
        {
            System.out.println("read"+message);
            incoming.append(message+"\n");

        }
}catch(Exception ex)
    {
    ex.printStackTrace();
    }
    }
}

}

1 个答案:

答案 0 :(得分:0)

您尚未在streamreader课程中初始化IncomingReader变量。在不初始化的情况下,run()方法会readLine()调用它。这就是你获得NPE的原因