简体   繁体   English

应用程序中的Java小程序

[英]Java applet in application

I've written a Snake clone in the process of learning how to program in Java. 我在学习如何使用Java编程的过程中编写了一个Snake克隆。 It is an applet that uses images (loaded in the init() method using getImage(getDocumentBase(), "gfx/image.png"); 它是一个使用图像的applet(使用getImage(getDocumentBase(),“gfx / image.png”)在init()方法中加载;

When I run the applet in my IDE (Eclipse) it runs fine and all the images are shown. 当我在我的IDE(Eclipse)中运行applet时,它运行正常并显示所有图像。

My goal however is to create an executable jar file that I can pass around easier than an applet. 然而,我的目标是创建一个可执行的jar文件,我可以比applet更容易传递。 So I created a new class and used a JPanel to host my applet. 所以我创建了一个新类并使用JPanel来托管我的applet。 Now the problem is that getDocumentBase() always returns null, resulting in the images not being found on the filesystem, resulting in an empty screen. 现在问题是getDocumentBase()总是返回null,导致在文件系统上找不到图像,导致空屏幕。

I know the game runs cause I can navigate all the menus and see all the text that is printed. 我知道游戏运行因为我可以导航所有菜单并查看所有打印的文本。 It's just the images that aren't loaded. 它只是未加载的图像。

Is there any way around this? 有没有办法解决? Should I load my images another way? 我应该以另一种方式加载图像吗?

Thanks 谢谢

You can load resources from within you jar-file by using the getResource() method from Class . 您可以使用ClassgetResource()方法从jar文件中加载资源。 On DevX there's a nice tutorial showing you how to do that for applets and applications: 在DevX上有一个很好的教程,向您展示如何为applet和应用程序执行此操作:

http://www.devx.com/tips/Tip/5697 http://www.devx.com/tips/Tip/5697

There is also an article from Oracle describing how to access resources in a location-independent manner: 还有一篇来自Oracle的文章描述了如何以与位置无关的方式访问资源:

http://download.oracle.com/javase/1.4.2/docs/guide/resources/resources.html http://download.oracle.com/javase/1.4.2/docs/guide/resources/resources.html

Basically you're accessing an image like this: 基本上你正在访问这样的图像:

URL myurl = this.getClass().getResource("/myimage.gif");
Toolkit tk = this.getToolkit();
img = tk.getImage(myurl);

Load your image like this instead: 像这样加载你的图像:

public void init() {
    URL url = getClass().getResource("/gfx/image.png");
    Image image = getImage(url);
}

Then add your gfx/image.png file to your jar and keep the path. 然后将gfx/image.png文件添加到jar中并保留路径。 Note that jar files are just zip files. 请注意,jar文件只是zip文件。

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

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