获得异常,: - java.lang.NullPointerException?

时间:2013-06-10 18:17:02

标签: java nullreferenceexception

获得以下例外: -

java.lang.NullPointerException
    at com.local.testing.ChatClient$sendButtonActionListener.actionPerformed(ChatClient.java:53)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

我使用以下两个类: -

package com.local.testing;

import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChatClient {
    JTextField outgoing=null;
    Socket sock=null;
    PrintWriter writer=null;
    public void buildGui(){
        JFrame frame = new JFrame("ChatClient");
        JPanel mainPanel = new JPanel();
        outgoing = new JTextField(20);
        JButton send = new JButton("send");
        send.addActionListener(new sendButtonActionListener());
        mainPanel.add(outgoing);
        mainPanel.add(send);
        frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
        frame.setVisible(true);
        frame.setSize(400, 400);
        frame.pack();

        setUpNetworking();
    }

    private void setUpNetworking(){
        try{
        sock  = new Socket("127.0.0.1",4242);
        writer = new PrintWriter(sock.getOutputStream());
        System.out.println("Connection Established");
    }
        catch(UnknownHostException uhe){
            uhe.printStackTrace();
        }
        catch(IOException ioe){
            ioe.getMessage();
        }
        finally{
            if(writer !=null){
                writer.close();
            }
        }
}
    public class sendButtonActionListener implements ActionListener{
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            //System.out.println(outgoing.getText());
            try{

            writer.println(outgoing.getText()); 
            writer.flush();
            }
            catch(Exception e){
                e.printStackTrace();
            }
            outgoing.setText("");
            outgoing.requestFocus();
        }
    }

    public static void main(String []x){
        ChatClient client = new ChatClient();
        client.buildGui();
    }
}

package com.local.testing;

import java.io.*;
import java.net.*;

public class ChatServer {

    public void connectToClient(){
        try {
            ServerSocket serverSocket = new ServerSocket(4242);
            while(true)
            {
                Socket sock = serverSocket.accept();
                InputStreamReader stream = new InputStreamReader(sock.getInputStream());
                BufferedReader reader = new BufferedReader(stream);
                String chat=reader.readLine();
                System.out.println(chat);
            }
        } 
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String [] x){
        ChatServer server = new ChatServer();
        server.connectToClient();
    }
}

可能是什么问题?

3 个答案:

答案 0 :(得分:1)

您的setUpNetworking方法存在问题。如果运行以下命令,您将看到它打印test/test2/null。所以你抓住了IOException,因此writer没有被初始化,这会抛出NPE

private void setUpNetworking(){
        System.out.println("test");
        try{
        sock  = new Socket("127.0.0.1",4242);
        writer = new PrintWriter(sock.getOutputStream());
        }
        catch(UnknownHostException uhe){
            System.out.println("test1");
            uhe.printStackTrace();
        }
        catch(IOException ioe){
            System.out.println("test2");
            ioe.getMessage();
        }
        finally{
            if(writer !=null){
                writer.close();
            }
        }
        System.out.println(writer);
}

如果您打印堆栈跟踪,则会得到:

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.local.testing.ChatClient.setUpNetworking(ChatClient.java:31)
at com.local.testing.ChatClient.buildGui(ChatClient.java:14)
at com.local.testing.ChatClient.main(ChatClient.java:62)

所以你必须解决这个错误。

答案 1 :(得分:0)

buildGui()初始化之前,您的事件处理程序似乎已被调用。所以基本上确保这个函数被调用,例如在构造函数中。

答案 2 :(得分:0)

writer.println(outgoing.getText()); 

编写器初始化为null,并且在调用之前从不设置为对象。(JTextField outgoing=null;