java - 聊天功能中出现 NullPointerException

标签 java swing nullpointerexception

public final class Mymain extends javax.swing.JFrame {

    public static String name = "";
    public String msg;
    public static String s = null;
    public static String talkto;
    XMPPConnection connection;

    public Mymain() throws NullPointerException, IOException, XMPPException {
        initComponents();
        welcome.setText(name);

    }

    public Mymain(String username, String password) throws IOException, XMPPException, NullPointerException, InterruptedException, InvocationTargetException {
        ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
        connection = new XMPPConnection(config);
        connection.connect();
        connection.login(username, password);
        name = username;

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new Mymain().setVisible(true);
                } catch (NullPointerException | IOException | XMPPException ex) {
                    Logger.getLogger(Mymain.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

    }

    public void begin_chat(String to) throws IOException, XMPPException, NullPointerException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        Chat chat = connection.getChatManager().createChat(to, new MessageListener() {

            @Override
            public void processMessage(Chat chat, Message msg) {
                if (msg.getType() == Message.Type.chat) {
                    if (msg != null && msg.getBody() != null) {
                        System.out.println(chat.getParticipant() + " says: "
                                + (msg != null ? msg.getBody() : "NULL"));
                    }
                }
            }
        });
        while ((msg = br.readLine()) != null) {

            chat.sendMessage(msg);
        }
        if (msg.equals("bye")) {
            connection.disconnect();
        }
    }

    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        welcome = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        tf1 = new javax.swing.JTextField();

        jLabel2.setText("jLabel2");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Ch@t Me!");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(0, 255, 204));

        jLabel1.setFont(new java.awt.Font("Comic Sans MS", 1, 18)); // NOI18N
        jLabel1.setText("Heya,");

        welcome.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N

        jSeparator1.setBackground(new java.awt.Color(0, 0, 0));
        jSeparator1.setForeground(new java.awt.Color(0, 0, 0));

        jLabel3.setFont(new java.awt.Font("Comic Sans MS", 1, 18)); // NOI18N
        jLabel3.setText("Buddies Online");

        tf1.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N
        tf1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(96, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(welcome, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(67, 67, 67))
                .addComponent(jSeparator1)
                .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(57, 57, 57)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(tf1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(390, 390, 390))
                );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(welcome, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(tf1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(235, 235, 235))
                );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
                );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
                );

        pack();
    }// </editor-fold>                        

    private void tf1ActionPerformed(java.awt.event.ActionEvent evt) {

        if (!(talkto = tf1.getText()).equals("")) {
            try {
                begin_chat(talkto);
            } catch (IOException | XMPPException | NullPointerException ex) {
                Logger.getLogger(Mymain.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public static void main(String args[]) {
    }
// Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    public static javax.swing.JTextField tf1;
    public static javax.swing.JLabel welcome;
// End of variables declaration                   
}

我在 Chat chat= 行的 begin_chat() 中收到空指针异常...我已经建立了连接..即使我收到异常..但是当我在begin_chat 函数,我收到illegela 监视器状态异常...有人请帮忙..

最佳答案

你有两个问题。首先,如果您不调用参数化构造函数,则永远不会创建连接,但如果您这样做,则会创建一个单独的 Mymain 实例,这意味着第二个实例没有有效连接,因为有效引用属于参数化实例

public Mymain(String username, String password) throws IOException, XMPPException, NullPointerException, InterruptedException, InvocationTargetException {
    ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
    connection = new XMPPConnection(config);
    connection.connect();
    connection.login(username, password);
    name = username;

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                // This is a new instance of MyMain, so the connection
                // you just created is relevant...
                new Mymain().setVisible(true);
            } catch (NullPointerException | IOException | XMPPException ex) {
                Logger.getLogger(Mymain.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}

首先删除默认构造函数并将其功能移至参数化构造函数

删除这个

public Mymain() throws NullPointerException, IOException, XMPPException {
    initComponents();
    welcome.setText(name);
}

并更新此...

public Mymain(String username, String password) throws IOException, XMPPException, NullPointerException, InterruptedException, InvocationTargetException {
    initComponents();
    welcome.setText(name);

    ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
    connection = new XMPPConnection(config);
    connection.connect();
    connection.login(username, password);
    name = username;

    setVisible(true);
}

更好的解决方案是首先创建连接,然后将其传递给 Mymain

例如...

public Mymain(XMPPConnection connection) {
    this.connection = connection;
    initComponents();
    setVisible(true);
}

try {

    String username, String password) throws IOException, XMPPException, NullPointerException, InterruptedException, InvocationTargetException {
    ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
    connection = new XMPPConnection(config);
    connection.connect();
    connection.login(username, password);
    new MyMain(connection);
} catch (IOException | XMPPException | NullPointerException | InterruptedException | InvocationTargetException exp) {
    exp.printStackTrace();
}

基于前面的示例,这对我来说效果很好......

public static void main(String args[]) {
    try {
        System.out.println("Connecting...");
        ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
        final XMPPConnection connection = new XMPPConnection(config);
        connection.connect();
        String userName = ...;
        String password = ...;
        connection.login(userName, password);

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                System.out.println("Connected...");
                Mymain mymain = new Mymain(connection);
            }
        });
    } catch (XMPPException exp) {
        exp.printStackTrace();
    }
}

关于java - 聊天功能中出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18941410/

相关文章:

java - 如何在 avro 模式中定义 byte[] 和 LocalDateTime?

java - 循环从字符串中一一删除字符

java - JLabel滚动后消失

java - 空指针运行时异常

java - 尝试在空对象引用上调用虚拟方法 'android.content.res.Resources$Theme android.content.Context.getTheme()'

java - 什么是NullPointerException,我该如何解决?

java - 将现有的maven项目添加到eclipse中的Maven多模块项目中

java - 如何为 Android 生成恒定的 UUId?

java - 如何删除 Accordion 标签上的数字?

java - JTextArea位置,setBounds不起作用?