我是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();
}
}
}
}
答案 0 :(得分:0)
您尚未在streamreader
课程中初始化IncomingReader
变量。在不初始化的情况下,run()
方法会readLine()
调用它。这就是你获得NPE的原因