线程“Timer-0”中的异常 java.lang.NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20080612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:57:53  来源:igfitidea点击:

Exception in thread "Timer-0" java.lang.NullPointerException

javaexceptiontimernullpointerexception

提问by user2933161

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 !

我有下面的代码,它向我显示了一个异常:线程“Timer-0”java.lang.NullPointerException 中的异常。错误在一行: jLabel1.setIcon(black); 如果我删除这一行,那么它运行良好。任何的想法?谢谢 !

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);
        }
    });
}

回答by DoubleDouble

Code either doesn't know what jLabel1is, or it doesn't know what blackis. Make sure both are Objects within view of that run() method.

代码要么不知道是什么jLabel1,要么不知道是什么black。确保两者都是该 run() 方法视野内的对象。