0

I'm trying to create an animation, and I'm creating an ImageIcon them setting it as an Icon for a JLabel. However, when I run the application, I get a run time exception that says my Image Icon is null
Heres my code:

public class Threader extends JFrame implements Runnable {
    Toolkit tk = Toolkit.getDefaultToolkit();
    int width = ((int) tk.getScreenSize().getWidth());//length of screen
    int height = ((int) tk.getScreenSize().getHeight());//height

    int x = width / 2;
    int y = height / 2;
    int bounce = 1;

    ImageIcon icon;
    JLabel ball;
    JPanel panel;

    public Threader() {
        super("Eph Studios Presents");
        icon = new ImageIcon(getClass().getResource("ball.png"));
        ball.setIcon(icon);
        panel = new JPanel();
        ball.setLocation(x / 2, y / 2);
        panel.add(ball);
        add(panel);
    }

    public void run() {
        panel.remove(ball);
        ball.setLocation(x, y);
        try {
            Thread.sleep(1);
        } catch (Exception e) {}
        if (x >= width || y >= height) {
            if (bounce > 4) {
                bounce = 1;
            } else {
                bounce++;
            }
        }
        if (bounce == 1) {
            x++;
            y++;
        } else if (bounce == 2) {
            x++;
            y--;
        } else if (bounce == 3) {
            x--;
            y--;
        } else if (bounce == 4) {
            x--;
            y++;
        }
        panel.revalidate();
        panel.repaint();
    }

}

And the error message:

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
    at main.Threader.<init>(Threader.java:22)
    at main.Animation.<clinit>(Animation.java:6)

My image is in the same package as the class so where am I going wrong?

  • 1
    Your question in a nutshell is why does `getClass().getResource("ball.png")` return null, and it's because ball.png is not to be found where you're looking for it. Please look at the [duplicate question link](http://stackoverflow.com/questions/15581687/class-getresource-returns-null) as well as [links to similar questions](https://www.google.com/webhp?sourceid=chrome-instant&rlz=1C1LEND_enUS445US445&ion=1&espv=2&ie=UTF-8#q=java+getresource+is+null+site:http:%2F%2Fstackoverflow.com%2F) to see the details of what's wrong. – Hovercraft Full Of Eels Aug 22 '15 at 16:15
  • 1
    Also have a look at the [Class API](http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) in particular its entry for [getResource()](http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResource-java.lang.String-) to see what Java has to say on the matter. – Hovercraft Full Of Eels Aug 22 '15 at 16:18

0 Answers0