简体   繁体   English

在JApplet中加载图像时出现空指针异常

[英]Null pointer exception while loading image in JApplet

I am gettting a nullpointer excetion when i run the applet in browser, while its working fine through appletviewer. 当我在浏览器中运行applet时,我正在获取nullpointer兴奋,而通过appletviewer可以正常工作。

 titleicon=new ImageIcon(this.getClass().getClassLoader().getResource("image.jpg"));
 img=new JLabel(titleicon)

File locations: Both .class file and image file are in same folder. 文件位置:.class文件和图像文件都在同一文件夹中。

C:\\project\\game.class C:\\ project \\ game.class
C:\\project\\image.jpg C:\\ project \\ image.jpg

I tried differennt variations below, none is working in browser but all are fine with appletviewer: 我在下面尝试了不同的变体,没有一个可以在浏览器中工作,但是使用appletviewer都可以:

 titleicon=new ImageIcon(this.getClass().getResource("image.jpg"));
 titleicon=new ImageIcon(getClass().getClassLoader().getResource("image.jpg"));

With a file location of 文件位置为

C:\project\game.class
C:\project\image.jpg

Class.getResource will never work, as this searches the classpath for the required resources. Class.getResource将永远无法工作,因为这会在类路径中搜索所需的资源。

The use of getResource assumes that the resources are embedded and are relative to the class path. 使用getResource假定资源是嵌入式的,并且相对于类路径。

Without more details, it's difficult to make an accurate suggestion, but I would suggest that you get the images jared without your application code, this way, it will be easier to find. 如果没有更多细节,很难提出准确的建议,但是我建议您在不使用应用程序代码的情况下获取图像,这将使查找起来更加容易。

If you're not using an IDE capable of Jaring your classes and resources, then you will need to have a look at Packaging Programs in JAR Files 如果您使用的不是具有Jaring类和资源功能的IDE,则需要查看JAR文件中的打包程序

Remember, Class#getResource is capable of doing a relative lookup. 记住, Class#getResource能够进行相对查找。 If the images are not stored in the same package as the class which is loading them, then you need to use an absolute path instead... 如果图像未与正在加载图像的类存储在同一包中,则需要使用绝对路径来代替...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM