线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException错误

时间:2014-01-20 07:21:33

标签: nullpointerexception runtime-error drjava awt-eventqueue

您好,我是一名高中水平的新程序员,因此我对编程知之甚少,并且遇到了一些已经解决的错误,而其他一些我完全不理解。我将制作一个简单的Check Box选择程序,用户可以在各种选择之间进行选择,并根据其动作改变图像。程序本身编译得很完美,但是当我运行它时,它给了我一些复杂性。这是我的计划:

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();
        }
    });
}
}

这部分运行得很顺利,但是当我继续运行程序时,我得到了这个错误。

> 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)

可能是一个愚蠢的错误,但我似乎无法弄清楚这一点。请帮忙,谢谢

     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("");
    }
} 

2 个答案:

答案 0 :(得分:23)

经常,

NullPointerException是更容易诊断的例外。每当你在Java中获得异常并且你看到堆栈跟踪(顺便说一下,你的第二个引用块是什么)时,你会从上到下阅读。通常,您会看到以Java库代码或本机实现方法开始的异常,对于诊断,您可以跳过这些异常,直到看到您编写的代码文件为止。

然后你喜欢在指定的行上查看该行上的每个对象(实例化的类) - 其中一个没有创建,你试图使用它。您可以首先查看代码,看看是否在该对象上调用了构造函数。如果你没有,那就是你的问题,你需要通过调用新的Classname(参数)来实例化该对象。当存在具有相同名称的实例变量时,NullPointerException s的另一个常见原因是意外地声明了具有局部范围的对象。

在您的情况下,在第75行的Workshop构造函数中发生了异常。<init>表示类的构造函数。如果您在代码中查看该行,则会看到

denimjeansButton.addItemListener(this);

这一行上有两个对象:denimjeansButtonthisthis与您当前所在的类实例同义,并且您在构造函数中,因此它不能是thisdenimjeansButton是你的罪魁祸首。你永远不会实例化那个对象。删除对实例变量denimjeansButton的引用或实例化它。

答案 1 :(得分:0)

在Public Workshop()的代码顶部附近,我假设这是

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


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

应该是

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


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