[nullpointerexception] Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Hello I'm a new programmer at an high school level as a result I do not know much about programming and am getting quite a few errors which have been resolved while others I completely do not understand. I am to make a simple Check Box selection program where the user gets to pick between a variety of choices and depending on their action the image changes. The program itself compiles perfectly but when I run it however it gives me some complications. Here is my program:

package components;

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

public class Workshop extends JPanel
                      implements ItemListener {
JCheckBox winterhatButton;
JCheckBox sportshatButton;
JCheckBox santahatButton;
JCheckBox redshirtButton;
JCheckBox brownshirtButton;
JCheckBox suitButton;
JCheckBox denimjeansButton;
JCheckBox blackpantsButton;
JCheckBox khakipantsButton;


    StringBuffer choices;
JLabel pictureLabel;

public Workshop() {
    super(new BorderLayout());

    //Create the check boxes.
    winterhatButton = new JCheckBox("Winter Hat");
    winterhatButton.setMnemonic(KeyEvent.VK_Q);


    sportshatButton = new JCheckBox("Sports Hat");
    sportshatButton.setMnemonic(KeyEvent.VK_W);


    santahatButton = new JCheckBox("Santa hat");
    santahatButton.setMnemonic(KeyEvent.VK_E);


    redshirtButton = new JCheckBox("Red Shirt");
    redshirtButton.setMnemonic(KeyEvent.VK_R);


    brownshirtButton = new JCheckBox("Brown Shirt");
    brownshirtButton.setMnemonic(KeyEvent.VK_T);


    suitButton = new JCheckBox("Suit");
    suitButton.setMnemonic(KeyEvent.VK_Y);


    suitButton = new JCheckBox("Denim Jeans");
    suitButton.setMnemonic(KeyEvent.VK_U);


    blackpantsButton = new JCheckBox("Black Pants");
    blackpantsButton.setMnemonic(KeyEvent.VK_I);


    khakipantsButton = new JCheckBox("Khaki Pants");
    khakipantsButton.setMnemonic(KeyEvent.VK_O);



    //Register a listener for the check boxes.

    winterhatButton.addItemListener(this);
    sportshatButton.addItemListener(this);
    santahatButton.addItemListener(this);
    redshirtButton.addItemListener(this);
    brownshirtButton.addItemListener(this);
    suitButton.addItemListener(this);
    denimjeansButton.addItemListener(this);
    blackpantsButton.addItemListener(this);
    khakipantsButton.addItemListener(this);


    //Indicates
    choices = new StringBuffer("---------");


    //Set up the picture label
    pictureLabel = new JLabel();
    pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));
    updatePicture();

     //Put the check boxes in a column in a panel
    JPanel checkPanel = new JPanel(new GridLayout(0, 1));
    checkPanel.add(winterhatButton);
    checkPanel.add(sportshatButton);
    checkPanel.add(santahatButton);
    checkPanel.add(redshirtButton);
    checkPanel.add(brownshirtButton);
    checkPanel.add(suitButton);
    checkPanel.add(denimjeansButton);
    checkPanel.add(blackpantsButton);
    checkPanel.add(khakipantsButton);


    add(checkPanel, BorderLayout.LINE_START);
    add(pictureLabel, BorderLayout.CENTER);
    setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}


    /** Listens to the check boxes. */
public void itemStateChanged(ItemEvent e) {
    int index = 0;
    char c = '-';
    Object source = e.getItemSelectable();

    if (source == winterhatButton) {
        index = 0;
        c = 'q';
    } else if (source == sportshatButton) {
        index = 1;
        c = 'w';
    } else if (source == santahatButton) {
        index = 2;
        c = 'e';
    } else if (source == redshirtButton) {
        index = 3;
        c = 'r';
    } else if (source == brownshirtButton) {
        index = 4;
        c = 't';
    } else if (source == suitButton) {
        index = 5;
        c = 'y';
    } else if (source == denimjeansButton) {
        index = 6;
        c = 'u';
    } else if (source == blackpantsButton) {
        index = 7;
        c = 'i';
    } else if (source == khakipantsButton) {
        index = 8;
        c = 'o';
    } 


    if (e.getStateChange() == ItemEvent.DESELECTED) {
        c = '-';
    }

    //Apply the change to the string.
    choices.setCharAt(index, c);

    updatePicture();
}


protected void updatePicture() {
    //Get the icon corresponding to the image.
    ImageIcon icon = createImageIcon(
                                "images/bear/bear-"
                                + choices.toString()
                                + ".gif");
    pictureLabel.setIcon(icon);
    pictureLabel.setToolTipText(choices.toString());
    if (icon == null) {
        pictureLabel.setText("Missing Image");
    } else {
        pictureLabel.setText(null);
    }
}

/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = Workshop.class.getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

  private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Build a Bear at Safeer's Workshop!");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JComponent newContentPane = new Workshop();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}

Well up to this part it runs smoothly and complies but when I proceed to run the program I get this error.

> run components.Workshop
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at components.Workshop.<init>(Workshop.java:75)
at components.Workshop.createAndShowGUI(Workshop.java:195)
at components.Workshop.access$0(Workshop.java:189)
at components.Workshop$1.run(Workshop.java:209)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(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)

Might be a silly mistake however I cant seem to figure this out. Please Help and thank you

     Here is the line that generates that error 
     private void jButtonSendActionPerformed(java.awt.event.ActionEvent evt)   {                                                
    // TODO add your handling code here:
    String message;
    if(messageBox.getText().length() > 0){
        message  =  messageBox.getText();
        chatBox.append(message+"\n"); 
        printStream.println(message);//this line 
        printStream.flush();
        //printStream.close();
        messageBox.setText("");
    }
} 

The answer is


NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.


Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

Examples related to nullpointerexception

Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Null pointer Exception on .setOnClickListener - java.lang.NullPointerException - setText on null object reference NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference Java 8 NullPointerException in Collectors.toMap NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

Examples related to runtime-error

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined' what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? javac: invalid target release: 1.8 C++ error : terminate called after throwing an instance of 'std::bad_alloc' Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error No Main class found in NetBeans Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0 TypeError: Cannot read property "0" from undefined Array Index Out of Bounds Exception (Java) Excel VBA Automation Error: The object invoked has disconnected from its clients

Examples related to drjava

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Examples related to awt-eventqueue

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error