我有一个小程序,里面有一些按钮,这些按钮有图像图标。我还用这个小程序制作了一个 HTML 文件。每当我从服务器(Apache tomcat)打开此页面时,都会发生异常:
java.lang.reflect.InvocationTargetException.
但是如果我在没有图标的情况下运行,就没有问题。谁能帮助我,以便我可以加载带有按钮图标的小程序?
Image myImage = getToolkit().createImage("image/REC1.jpg");
ImageIcon myIcon = new ImageIcon(myImage);
button.setIcon(myIcon);
最佳答案
Returns an image which gets pixel data from the specified file. The returned Image is a new object which will not be shared with any other caller of this method or its getImage variant.
This method first checks if there is a security manager installed. If so, the method calls the security manager's
checkRead
method with the specified file to ensure that the image creation is allowed.
我将两部分加粗:
- 文件 - 只指向运行小程序的计算机的本地文件系统。因此不适合小程序中的图标 - 它们必须位于服务器上。还有..
- 安全管理器 - 不允许沙盒小程序读取或写入本地文件系统。这可能是堆栈跟踪中丢失的重要部分。
小程序资源访问
小程序需要通过URL 从“主服务器”加载资源(如果是沙盒)。
图标可能是嵌入资源,位于 applet
元素的 archive
属性中引用的 Jar 内,但如果它们作为图像加载到服务器,则它们可以相对于文档库或代码库进行访问。以下是包含 HTML 的目录的 image
子目录中名为 REC1.jpg
的图像的外观。
URL url = new URL(getDocumentBase(), "image/REC1.jpg");
Image myImage = getToolkit().createImage(url);
关于java.lang.reflect.InitationTargetException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11325466/