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