0

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?

BackSlash
  • 21,927
  • 22
  • 96
  • 136
K327
  • 308
  • 4
  • 10

3 Answers3

2

With the problem as you describe it relative path should be ./src/test/f.png (eclipse starts the application from the relative $project_loc, which is the root folder for your project)

Consider instead using a resources folder eg. src/resources/ or lib/ for your images/other resources.

blgt
  • 8,135
  • 1
  • 25
  • 28
  • so you mean i should make another folder then put image in it and again run? – K327 Sep 13 '13 at 13:52
  • Pretty much, yes. And update the paths inside your program. Best if you stick them in `static final` fields. – blgt Sep 13 '13 at 13:56
1

You use a relative path "f.png", and the class is in package (directory) first. So use "/test/f.png". (And be sure everything is case-sensite.)

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Open the produced jar, with 7zip/WinZip or so, and check the directories. The directory `src/test` normally is for unit tests, so place the images in src/resources or so. – Joop Eggen Sep 13 '13 at 13:40
0

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

K327
  • 308
  • 4
  • 10