Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8812005
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T03:30:10+00:00 2026-06-14T03:30:10+00:00

I made a small program that listens and sends lines on a tcp socket

  • 0

I made a small program that listens and sends lines on a tcp socket and appends the received info to a JTextArea. I use this to chat on a Minecraft server without having the game open.

I was working fine last night, but when I got up it wasn’t working. When I opened netbeans and ran it, it gave this error:

Exception in thread "main" java.lang.NullPointerException
    at com.xxx.mcchat.chat.main(chat.java:333)

Can anyone explain what’s wrong?

Here is the code (http://pastebin.com/FPNty0qf):

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xxx.mcchat;

import java.io.*;
import java.net.*;
import net.sf.json.*;
import org.apache.commons.beanutils.*;
import org.apache.commons.collections.*;
import org.apache.commons.lang.*;
import net.sf.ezmorph.*;
import org.apache.commons.logging.*;
import java.awt.event.*;
import javax.swing.UIManager;
/**
 *
 * @author xxx
 */
public class chat extends javax.swing.JFrame {

    /**
     * Creates new form chat
     */

    public chat() {
        initComponents();
    }

    public void send(String user, String message){
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;


        try {
            socket = new Socket("mc.xxx.net", 20060);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection");
            System.exit(1);
        }

        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

                //System.out.println(in.readLine()); //Uncomment to debug
        if(username != null){
            out.println("/api/call?method=broadcast&args="+"[\"§7[Web] §b"+username+"§7:§f "+message+"\"]"+"&key=f0e2ad47a9a43c783d2c54f396f655c9279829c8c69ae9f52934648098dec993");
            chatArea.append(username + ": " + message + "\n\r");
            if(autoscrollCheck.isSelected()){
                chatArea.setCaretPosition(chatArea.getText().length() - 1);
            }
        }else{
            chatArea.append("You must set your username!!" + "\n\r");
            if(autoscrollCheck.isSelected()){
                chatArea.setCaretPosition(chatArea.getText().length() - 1);
            }

        }
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                       
    private void initComponents() {

        jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
        jToggleButton1 = new javax.swing.JToggleButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        chatArea = new javax.swing.JTextArea();
        input = new javax.swing.JTextField();
        send = new javax.swing.JButton();
        user = new javax.swing.JTextField();
        userset = new javax.swing.JButton();
        autoscrollCheck = new javax.swing.JCheckBox();
        jLabel1 = new javax.swing.JLabel();

        jCheckBoxMenuItem1.setSelected(true);
        jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");

        jToggleButton1.setText("jToggleButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Minecraft Chat");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        chatArea.setEditable(false);
        chatArea.setBackground(new java.awt.Color(0, 0, 0));
        chatArea.setColumns(20);
        chatArea.setFont(new java.awt.Font("Consolas", 0, 14)); // NOI18N
        chatArea.setForeground(new java.awt.Color(255, 255, 255));
        chatArea.setLineWrap(true);
        chatArea.setRows(5);
        jScrollPane1.setViewportView(chatArea);

        input.setToolTipText("Enter message here");
        input.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputKeyPressed(evt);
            }
        });

        send.setText("Send");
        send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendActionPerformed(evt);
            }
        });

        user.setToolTipText("");
        user.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                userActionPerformed(evt);
            }
        });
        user.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                userKeyPressed(evt);
            }
        });

        userset.setText("Set");
        userset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usersetActionPerformed(evt);
            }
        });

        autoscrollCheck.setSelected(true);
        autoscrollCheck.setText("Auto Scroll");
        autoscrollCheck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                autoscrollCheckActionPerformed(evt);
            }
        });

        jLabel1.setText("Enter Username:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(user, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(userset)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(autoscrollCheck))
                    .addComponent(jScrollPane1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(input, javax.swing.GroupLayout.PREFERRED_SIZE, 649, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(send)))
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(user, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)))
                    .addComponent(userset)
                    .addComponent(autoscrollCheck))
                .addGap(6, 6, 6)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(send))
                .addGap(11, 11, 11))
        );

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

    String username = null;
    private void inputKeyPressed(java.awt.event.KeyEvent evt) {                              
           int key = evt.getKeyCode();
           if (key == KeyEvent.VK_ENTER) {  
                send(username, input.getText());
                input.setText("");
              }
    }                               

    private void sendActionPerformed(java.awt.event.ActionEvent evt) {                                   
        send(username, input.getText());
        input.setText("");
    }                                   

    private void usersetActionPerformed(java.awt.event.ActionEvent evt) {                                       
        if(username == null){
                    if(!"".equals(user.getText())){
                        username = user.getText();
                        chatArea.append("Username set!"+"\n\r");
                        if(autoscrollCheck.isSelected()){
                            chatArea.setCaretPosition(chatArea.getText().length() - 1);
                        }
                    }else{
                        chatArea.append("Username can not be blank."+"\n\r");
                        if(autoscrollCheck.isSelected()){
                            chatArea.setCaretPosition(chatArea.getText().length() - 1);
                        }
                    }
                }else{
                    send(username, "§7changed name to " + user.getText());
                    username = user.getText();
                }
    }                                      

    private void userActionPerformed(java.awt.event.ActionEvent evt) {                                   
        // TODO add your handling code here:
    }                                   

    private void userKeyPressed(java.awt.event.KeyEvent evt) {                              
           int key = evt.getKeyCode();
           if (key == KeyEvent.VK_ENTER) {  
                if(username == null){
                    if(!"".equals(user.getText())){
                        username = user.getText();
                        chatArea.append("Username set!"+"\n\r");
                        if(autoscrollCheck.isSelected()){
                            chatArea.setCaretPosition(chatArea.getText().length() - 1);
                        }
                    }else{
                        chatArea.append("Username can not be blank."+"\n\r");
                        if(autoscrollCheck.isSelected()){
                            chatArea.setCaretPosition(chatArea.getText().length() - 1);
                        }
                    }
                }else{
                    send(username, "§7changed name to " + user.getText());
                    username = user.getText();
                }
              }
    }                              

    private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   

    }                                 

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                               
        // TODO add your handling code here:
    }                                

    private void autoscrollCheckActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
    }                                              

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws IOException {

        /* Set the system look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new chat().setVisible(true);
            }
        });
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;


        try {
            socket = new Socket("mc.xxx.net", 20060);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection");
            System.exit(1);
        }

        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

                //System.out.println(in.readLine()); //Uncomment to debug

        out.println("/api/subscribe?source=chat&key=1e287587f5d1d45255f4708467eeaf8a71085f9ccfd8a354523d233cf5a77be4&show_previous=true");
        out.println("/api/subscribe?source=connections&key=e410592b70c0288654e6c1040edb0f21811dcb3f2ee11051163f36be9be00788&show_previous=false");

        while(true){
            String jsonString = in.readLine();
            JSONObject obj = JSONObject.fromObject(jsonString); 
            JSONObject success = obj.getJSONObject("success");
            if(success.get("message") != null){
                chatArea.append("<" + success.get("player") + "> " + success.get("message") + "\n\r");
                if(autoscrollCheck.isSelected()){
                    chatArea.setCaretPosition(chatArea.getText().length() - 1);
                }
            }else if (success.get("action") != null){
                chatArea.append(success.get("player") + " " + success.get("action") + "\n\r");
                if(autoscrollCheck.isSelected()){
                    chatArea.setCaretPosition(chatArea.getText().length() - 1);
                }
            }
        }
    }

    // Variables declaration - do not modify                     
    public static javax.swing.JCheckBox autoscrollCheck;
    public static javax.swing.JTextArea chatArea;
    private javax.swing.JTextField input;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JButton send;
    private javax.swing.JTextField user;
    private javax.swing.JButton userset;
    // End of variables declaration                


}

(P.S Please don’t get grumpy because I’m using a GUI generator, this is my first program, I promise I will learn to do it by hand )

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T03:30:11+00:00Added an answer on June 14, 2026 at 3:30 am

    It is probably a race condition which makes it work sometimes. The variable chatArea is not guaranteed to be initialized by the time the main thread gets to line 333. This is due to the deferred initialization of the GUI via invokeLater() some lines before that:

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new chat().setVisible(true);
        }
    });
    

    You need some synchronization between those threads, or, what also should work, just initialize the GUI in the main thread:

    final chat chatObject = new chat();
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            chatObject.setVisible(true);
        }
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have made a small program in C# that I want to run in
I made this small Java program using eclipse IDE. I have set the workspace
I am having some issues with a small program I have made that edits
I have made a demo small program that I want to deliver to my
I've made a small application for class that works like this: you click any
I made a small test program that multiplies and adds 10 million numbers. With
I have a problem with a small program that i made. Below is the
I made a small Java program that loads a words list from a txt
I made small program to divide large pictures and take part of them. When
I've made a small program which has 2 buttons and each does certain thing.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.