Search code examples
javaeclipseswingpathimageicon

can not detect image in java


i want to make a simple Widget that has a combobox that can change picture. i have 2 png picture in src/test (beside my .java files)

when i run my program i receive this exceptions :

Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at first.gui.<init>(gui.java:11)
at first.Main.main(Main.java:11)

and this is my codes:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;

public class gui extends JFrame {

    JLabel lb = new JLabel();
    Icon[] pics = {
        new ImageIcon(getClass().getResource("f.png")),
        new ImageIcon(getClass().getResource("i.png"))
    };
    String[] str = {
        "f.png", "i.png"
    };

    JComboBox box = new JComboBox(str);

    public gui() {

        super("title");

        setLayout(new FlowLayout());
        box.addItemListener(
            new ItemListener() {
                public void itemStateChanged(ItemEvent event) {


                    if (event.getStateChange() == ItemEvent.SELECTED)

                        lb.setIcon(pics[box.getSelectedIndex()]);
                }
            });
        add(box);
    }
}

what should i do to solve it?


Solution

  • i have done this and it makes my code write

    the only thing that i should do is :

    putting my images in

    project_name/bin/test
    

    where my .class files are after that it can recognize the source