简体   繁体   中英

setIconImage intellij Project javax.swing

i'm heaving a problem in setting the icon for my swing project in intellij.

I tried this

iconpath = execPath + File.separator +  "images" + File.separator + "icon.png";

this.setIconImage(new ImageIcon(getClass().getResource(iconpath)).getImage());

but got

java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
    at cgui.FormApp.<init>(FormApp.java:52)
    at controller.Main.<clinit>(Main.java:39)
Exception in thread "main"

and

iconpath = execPath + File.separator +  "images" + File.separator + "icon.png";
InputStream resource = getClass().getResourceAsStream(iconpath);

Image image = null;
try {
      image = ImageIO.read(resource);
} catch (IOException e) {
  e.printStackTrace();
}
this.setIconImage(new ImageIcon(image).getImage());

and got

java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalArgumentException: input == null!
    at javax.imageio.ImageIO.read(ImageIO.java:1348)
    at cgui.FormApp.<init>(FormApp.java:58)
    at controller.Main.<clinit>(Main.java:39)
Exception in thread "main" 

I have my project structured like. Do you guys have any idea to how make this work?

项目文件夹结构

You get the image path relative to Main.java.

You should get the image from the absolute path with getClassLoader() .

this.setIconImage(new ImageIcon(getClass().getClassLoader().getResource("images/icon.png")).getImage());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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