0

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:

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);
    }
}
2
  • Try breaking it up. Define the member as uninitialized (private Icon[] pics;) then in the constructor do three different lines, first (pics = new Icon[2]), then (pics[0] = new ImageIcon(getClass().getResource(filename[0]))) This should help tell you where the problem is. You can even break up the getClass() and getResource() calls to different lines which might narrow down the issue Commented Jan 25, 2014 at 2:41
  • That's a good idea ill try that now Commented Jan 25, 2014 at 2:41

1 Answer 1

2

Turns out that my two resource files x.png and b.png were in the project folder rather then the package folder. Sorry for wasting your time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.