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?