【问题标题】:Null Pointer Exception Issue [closed]空指针异常问题[关闭]
【发布时间】:2013-07-19 19:21:32
【问题描述】:

我最初使用一个名为 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)

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

【问题讨论】:

  • BalusC 感谢您的编辑,但您知道我的问题的答案吗?
  • 我一般对回答这类极其琐碎的 Java 问题不感兴趣。你问这个问题的方式好像你已经不明白NullPointerException 的意思。您没有明确询问为什么特定对象引用是null。您很快就会很容易地得到 10 个答案,说出相同的答案或至少一两个答案并获得大量赞成票。
  • 我知道空指针异常错误是什么意思 BalusC。我只是问为什么我的代码中有一个。如果我不明白为什么我的代码首先会返回该结果,我怎么能问它为什么“明确”为空?

标签: java swing nullpointerexception jtextarea styleddocument


【解决方案1】:
    StyledDocument doc = chatWindow.getStyledDocument();

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

    StyledDocument doc;  

以便您以后可以参考。引用 cmets 的话:

chatWindow 在构造函数中初始化。但是 构造函数外部的初始化发生得更早,并且 chatWindow 当时为空。

【讨论】:

  • 部分正确,关于“从未初始化”:chatWindow 在构造函数中初始化。但是构造函数外部的初始化发生得更早,并且chatWindow那个时间为空。
  • @Andreas_D 啊,是的,将您的评论添加到我的主要答案中以帮助未来的访问者。
  • @user2596934 如果这是正确答案,请将其标记为已接受。
  • 抱歉,我该怎么做?我是新手。
  • @user2596934 得分计数下方的绿色复选标记(向上/向下箭头所在的位置)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2011-10-19
相关资源
最近更新 更多