简体   繁体   English

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

[英]Exception in thread “main” java.lang.NullPointerException Java GUI

I am learning the basics of GUI Java on eclipse however whenever I seem to compile this program I get the compiler error message of: 我正在学习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)

I looked for anything from the line the error originated from but I cant seem to find anything wrong with it: 我从错误起源的那一行寻找任何东西,但我似乎无法找到它的任何错误:

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

Any input on my error would be greatly appreciated. 我的错误的任何输入将不胜感激。 And here is the full code if it will help: 如果有帮助,这里是完整的代码:

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

Turns out that my two resource files x.png and b.png were in the project folder rather then the package folder. 事实证明,我的两个资源文件x.pngb.png位于项目文件夹中,而不是包文件夹中。 Sorry for wasting your time. 抱歉浪费你的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM