大家。
我是Java新手,用UI制作培训项目。 在培训过程中,我决定从资源中加载图标并在不同的类中移动它的加载。 并有问题。 我真的试图自己找到答案但不能。找到吼声。
主要课程
package scv.paul;
…
/**
* Create the application.
*/
public TestApp() {
Logger.getLogger(loggerName).fine("Showing main window");
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("Test App");
**frame.setIconImage( MyImages.appIcn.getImage());**//here try to load icon
获得例外:
线程“AWT-EventQueue-0”中的异常java.lang.ExceptionInInitializerError
实用程序类
package scv.paul;*
import javax.swing.ImageIcon;
public class MyImages {
public static final ImageIcon appIcn = new ImageIcon ( MyImages.class.getResource ( "AppIcon.png" ) );
public static final ImageIcon BtnIcn = new ImageIcon ( MyImages.class.getResource ( "OK.png" ) );
public static final ImageIcon exitIcn = new ImageIcon ( MyImages.class.getResource ( "door.png" ) );
}
图片位于“\ bin”文件夹
我理解静态字段初始化的问题。但无法理解原因。
如果我甚至调用这样的静态字段
,我就会收到此错误public static final String imgPath = System.getProperties().getProperty("user.dir")+"\\img\\";
但是如果我在主类中调用这个静态字段
,我就没有错误 public static final String imgPath = "c://myProjectPath//bin";
我找不到如何在良好的阶梯中使用资源。我在哪里读到它?
答案 0 :(得分:1)
不要像这样使用静态变量。无需保留对图标的引用。只需阅读图标并将其添加到按钮即可。
只需在类的构造函数中加载图像(创建按钮时)。有关更多信息和工作示例,请参阅How to Use Icons上Swing教程中的部分。
本教程还将向您展示如何更好地构建代码,以便在Event Dispatch Thread上创建Swing组件。
为其他Swing基础知识保留教程的链接。
答案 1 :(得分:0)
将图像放在投影目录中,例如bin和src文件夹所在的位置。
最好使用静态方法读取文件以及它们失败。假设您在名为resources的目录中的资源文件夹,您的代码看起来像这样。
public static ImageIcon makeImageIcon(String filename) {
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("resources/" + filename));
} catch (IOException e) {
e.printStackTrace();
}
return new ImageIcon(myPicture);
}
然后使用您想要的文件名调用此方法。
public static ImageIcon image= makeImageIcon("myImage.png");
希望这有帮助。