简体   繁体   English

将图标添加到 JFrame 时出现问题

[英]Problem in adding Icon to a JFrame

I have tried several methods to add an Icon to a JFrame.我尝试了几种方法将图标添加到 JFrame。 Every method work perfectly when I run it using the source code.当我使用源代码运行它时,每种方法都能完美运行。

for example:例如:

jframe.setIconImage(Toolkit.getDefaultToolkit().getImage("iconimages/icon.png"));

But none of them work when I run it using the jar file.但是当我使用 jar 文件运行它时,它们都不起作用。 I know the problem is with the path of the image file.我知道问题出在图像文件的路径上。 How can I solve this?我该如何解决这个问题?

Edit:编辑:

public Ui() { 
   initComponents(); 
   setLocationRelativeTo(null); 
   this.setIconImage(getImageIcon("icon.png").getImage());
} 

private ImageIcon getImageIcon(String fileName) {
   String imageDirectory = "iconimages/"; 
   imgURL = getClass().getResource(imageDirectory + fileName); 
   return new ImageIcon(imgURL); 
}

I tried this but now I get a null pointer exception.我试过这个,但现在我得到一个 null 指针异常。

--------------------------------------------------------------------------------

Edit [Solution]: I found the solution.编辑[解决方案]:我找到了解决方案。

I added ../ to the path additionally and it works perfectly:!!我另外添加了../到路径中,它完美地工作:!! :D :D

 ImageIcon imageIcon = new ImageIcon("../imageicons/icon.png");
 this.setIconImage(imageIcon.getImage());

Thanks all for try to help me.感谢大家尝试帮助我。 :) :)

You should use a URL.您应该使用 URL。 Like this:像这样:

 /**
  * Loads and returns an {@link Image} resource. 
  * @param fileName name of the image resource.
  * @return Image as resource.
  */
  public Image getResourceImage(String fileName) {
      String imageDirectory = "images/";
      URL imgURL = getClass().getResource(imageDirectory + fileName);
      Image image = null;
      try {
         image = ImageIO.read(imgURL);
       } catch (IOException e) {}
      return image;
    }

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

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