线程“ AWT-EventQueue-0”中的异常java.lang.NullPointerException在javax.swing.ImageIcon。(ImageIcon.java:205)
JLabel background = new JLabel(new ImageIcon(getClass().getResource("/resources/splashscreen.jpeg")));
上面的行是抛出异常的确切行,它使我相信文件的位置不正确,但是我尝试了很多事情,但都没有成功。
文件夹结构似乎是正确的,该图像位于项目文件夹内的resources文件夹内,并且该文件夹(带有图像)位于src文件夹旁边,而不在其中。此应用程序必须具有脱机使用的功能,否则我将只使用URL。 Eclipse IDE中是否存在与此相关的已知错误?
想通了。看来我将文件放置在错误的位置,并与.class文件放在一起解决了该问题。不知道这是一个适当的解决方案还是不幸的是只能解决。我不得不回到基础知识上。.java文件已编译,.class文件实际上正在运行,我需要从当前工作目录中回溯。
尝试此操作,将图像放置在名为Images的外部文件夹outside源文件夹中然后尝试:
public class Test{
public Test()
{
JFrame frame= new JFrame();
JLabel label = new JLabel(new ImageIcon("Images/image.jpeg"));
frame.getContentPane().add(label);
Container log = login.getContentPane();
log.setBackground(Color.WHITE);
frame.setVisible(true);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args)
{
new Test();
}
尝试启动此应用。
实际上,在这种情况下,您必须将“ resource”文件夹放入源文件夹。
似乎是“ /resources/splashscreen.jpeg”是绝对路径。尝试不使用前导斜线或给出“真实的”绝对路径。
编辑:我很确定没有找到该文件,并且getResource()返回null。
为什么不尝试获取文件大小?摆弄这个:
File f = new File("/resources/splashscreen.jpeg");
long length = f.length();
直到长度!= 0
:-)
我只是摆弄着同样的问题,@OiRC的回答对我很有帮助。我按照youtube教程获取代码,如下所示:
ImageIcon helpIcon = new ImageIcon(getClass().getResource("helpIcon.png"));
lbl_helpIcon = new JLabel(new ImageIcon("helpIcon.png"));
lbl_helpIcon.setBounds(178, 11, 139, 62);
lbl_helpIcon.setIcon(helpIcon);
我一直在获得NullPointerException异常>
ImageIcon helpIcon = new ImageIcon(getClass().getResource("helpIcon.png"));
直到我尝试过为止
lbl_helpIcon = new JLabel(new ImageIcon("helpIcon.png"));
lbl_helpIcon.setBounds(178, 11, 139, 62);