I have the code below,and it shows me an exception which is: Exception in thread "Timer-0" java.lang.NullPointerException. The erros is in line : jLabel1.setIcon(black); If I delete this line,then it works well. Any idea? Thank you !
Icon black=createImageIcon("black.PNG");
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Frame1.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public Frame1(int seconds) {
timer = new Timer();
timer.schedule(new RunMeTask(), 1000,1000);
}
public class RunMeTask extends TimerTask {
public int k=0;
public void run() {
System.out.println("Run Me ~");
jLabel1.setIcon(black); //error
k++;
if (k==10) {
timer.cancel();
}
}
}
public static void main(String args[]) {
new Frame1(1);
System.out.format("Task scheduled.%n");
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame1().setVisible(true);
}
});
}