空指针异常问题

时间:2013-07-19 19:21:32

标签: java swing nullpointerexception jtextarea styleddocument

我最初使用名为chatWindow的JTextArea创建了一个即时消息程序。我稍后将其更改为JTextPane。添加我的样式属性后,我在eclipse的控制台中得到了一个空指针异常。这是我的构造函数和方法类的代码:

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

    import javax.swing.*;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;

    public class Server extends JFrame{

        private JTextField userText;

        private JTextPane chatWindow;

        StyledDocument doc = chatWindow.getStyledDocument();

        //Defining attributes to varibles (keyword)
        SimpleAttributeSet keyWord = new SimpleAttributeSet();



        private ObjectOutputStream output;
        private ObjectInputStream input;
        private ServerSocket server;
        private Socket connection;

        //constructor
        public Server(){
            super("Mikey Mac Instant Messenger");
            userText = new JTextField();
            userText.setEditable(false);
            userText.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent event){
                        sendMessage(event.getActionCommand());
                        userText.setText("");
                    }
                }
            );
            add(userText, BorderLayout.NORTH);
            chatWindow = new JTextPane();
            chatWindow.setBackground(Color.getHSBColor(207, 24, 87));
            add(new JScrollPane(chatWindow));
            setSize(850,600);
            setVisible(true);
        }

        //set up and run the server
        public void startRunning(){
            try{
                server = new ServerSocket(6789, 100);
                while(true){
                    try{
                        waitForConnection();
                        setupStreams();
                        whileChatting();
                    }catch(EOFException eofException){
                        showMessage("\n SYSTEM - Server ended the connection!");
                    }finally{
                        closeWindow();
                    }
                }
            }catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
        //wait for connection, then display connection information
        private void waitForConnection() throws IOException{
            chatWindow.setEditable(false);
            showMessage("SYSTEM - Waiting for someone to connect... \n");
            connection = server.accept();
            showMessage("SYSTEM - Now connected to " + connection.getInetAddress().getHostName());
        }

        //get stream to send and recieve data
        private void setupStreams() throws IOException{
            output = new ObjectOutputStream(connection.getOutputStream());
            output.flush();
            input = new ObjectInputStream(connection.getInputStream());
            showMessage("\n SYSTEM - Streams are now setup! \n");
        }

        //during the chat conversation
        private void whileChatting() throws IOException{
            String message = " SYSTEM - You are now connected!";
            sendMessage(message);
            ableToType(true);
            do{
                //have a conversation
                try{
                    message = (String) input.readObject();
                    showMessage("\n" + message);
                }catch(ClassNotFoundException classNotFoundException){
                    showMessage("\n SYSTEM - I have no clue what the user just said!");
                }
            }while(!message.equals("CLIENT - END"));
        }

        //close streams and sockets after you are done chatting
        private void closeWindow(){
            showMessage("\n SYSTEM - Closing Connections... \n");
            ableToType(false);
            try{
                output.close();
                input.close();
                connection.close();
            }catch(IOException ioException){
                ioException.printStackTrace();
            }
        }

        //send message to client
        private void sendMessage(String message){
            try{

                output.writeObject("SERVER - " + message);
                output.flush();
                showMessage("\nSERVER - " + message);
            }catch(IOException ioException){
                //chatWindow.append("\n System Error: Dude I can't send this...");

                try
                {
                    StyleConstants.setForeground(keyWord, Color.getHSBColor(351, 95, 95));
                    StyleConstants.setBackground(keyWord, Color.YELLOW);
                    StyleConstants.setBold(keyWord, true);

                    doc.insertString(0, "System Error: Dude, I can't send this...", keyWord );
                }
                catch(Exception e) { System.out.println(e); }
            }
        }

        //updates chatWindow
        private void showMessage(final String string){
            SwingUtilities.invokeLater(
                new Runnable(){
                    public void run(){
                        //chatWindow.append(string);
                        //THE BOTTOM METHOD IS USED FOR APPENDING A STRING JTEXTPANE STYLE HAHA
                        try
                        {
                            //doc.insertString(0, "Start of text\n", null );
                            //doc.insertString(doc.getLength(), "", string );
                            //doc.insertString(int offset, String str, ArributeSet a);

                            //SETTING THE STYLE FOR THE STRING (down below)

                            StyleConstants.setForeground(keyWord, Color.getHSBColor(251, 89, 87));
                            //StyleConstants.setBackground(keyWord, Color.YELLOW);
                            StyleConstants.setBold(keyWord, false);

                            doc.insertString(0, string, keyWord);
                        }
                        catch(Exception e) { System.out.println(e); }
                    }
                }
            );
        }

        //let the user type stuff into their box
        private void ableToType(final boolean tof){
            SwingUtilities.invokeLater(
                    new Runnable(){
                        public void run(){
                            userText.setEditable(tof);
                        }
                    }
                );
        }

    }

这是我的主方法类的代码:

    import javax.swing.JFrame;

    public class ServerTest {
        public static void main(String[] args) {

            Server messaging = new Server();
            messaging.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            messaging.startRunning();
        }

    }

我在2个位置获取空指针异常:

 - The first one is here (In constructor): 
   **`StyledDocument doc = chatWindow.getStyledDocument();`**

 - The second one is here (In main): 
   **`Server messaging = new Server();`**

以下是我的控制台中消息所说的内容:

Exception in thread "main" java.lang.NullPointerException
    at Server.<init>(Server.java:18)
    at ServerTest.main(ServerTest.java:6)

有谁知道如何解决这个空指针异常错误?感谢。

1 个答案:

答案 0 :(得分:4)

    StyledDocument doc = chatWindow.getStyledDocument();

是因为你从未初始化chatWindow。将上面的初始化代码移动到构造函数中,它应该没问题。您需要保留成员变量声明:

    StyledDocument doc;  

以便您以后可以参考。引用评论:

  

chatWindow get在构造函数中初始化。但是   构造函数之外的初始化发生在早期和chatWindow之前   当时为空。