线程“main”中的异常java.lang.NullPointerException Java GUI

时间:2014-01-25 02:35:32

标签: java swing

我正在eclipse上学习GUI Java的基础知识但是每当我好像编译这个程序时,我都会收到编译器错误消息:

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at ClassTwo.<init>(ClassTwo.java:11)
    at ClassOne.main(ClassOne.java:6)

我从错误产生的那一行寻找任何东西,但我似乎无法发现它有什么问题:

private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])),new ImageIcon(getClass().getResource(filename[1]))};

我的错误的任何输入将不胜感激。如果有帮助,这里是完整的代码:

//ClassOne.Java
import javax.swing.JFrame;

class ClassOne {
    public static void main(String[] args){

        ClassTwo go = new ClassTwo();
        go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        go.setSize(300,200);
        go.setVisible(true);
    }
}


//ClassTwo.Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ClassTwo extends JFrame {

    private JComboBox box;
    private JLabel picture;

    private static String[] filename = {"b.png", "x.png"};
    private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0])),new ImageIcon(getClass().getResource(filename[1]))};

    public ClassTwo(){
        super("Title");
        setLayout(new FlowLayout());

        box = new JComboBox(filename);

        box.addItemListener(
                new ItemListener(){ //anonymous class that implements item listener 
                    public void itemStateChanged(ItemEvent event){
                        if(event.getStateChange()==ItemEvent.SELECTED) //what was selected
                            picture.setIcon(pics[box.getSelectedIndex()]);
                    }
                }
        );

        add(box);
        picture=new JLabel(pics[0]);
        add(picture);
    }
}

1 个答案:

答案 0 :(得分:2)

原来我的两个资源文件 x.png b.png 位于项目文件夹中,而不是包文件夹中。抱歉浪费你的时间。