简体   繁体   English

JFrame的图标无法显示

[英]JFrame's icon not displaying

I've got a Java application with Swing's JFrame as a main GUI unit. 我有一个使用Swing的JFrame作为主GUI单元的Java应用程序。 I've set the icon to it via setIconImage(). 我通过setIconImage()为它设置了图标。 When I run this program in NetBeans, everything works fine and the frame's icon displays. 当我在NetBeans中运行此程序时,一切正常,并显示框架的图标。 But when I compile it and try to run jar-file (with JRE7), the application has standard icon with Duke. 但是当我编译它并尝试运行jar文件(使用JRE7)时,应用程序具有Duke的标准图标。 How do I change that icon when running app outside NetBeans? 在NetBeans之外运行应用程序时如何更改该图标?

UPD: OK, here's the code: UPD:好的,这是代码:

public static void main(String[] args) throws IOException{
    URL imgUrl = Polygon.class.getResource("/imgs/icon.png");
    Image img = ImageIO.read(imgUrl);

    JFrame f = new JFrame();
    f.setSize(new Dimension(500, 500));
    f.setIconImage(img);
    f.setVisible(true);
}

UPD2: I've added this line to the end of the code: UPD2:我已将此行添加到代码的末尾:

    JOptionPane.showMessageDialog(null, new ImageIcon(img));

Everything's fine with the image! 一切都很好的形象! It loads! 加载! BUT it's not displayed as the icon. 但它没有显示为图标。

When you run the application from inside Netbeans, the files from your project folder are available, but if you run the compiled JAR yourself they may not. 从Netbeans内部运行应用程序时,项目文件夹中的文件可用,但如果您自己运行已编译的JAR,则可能不会。

Read this example (note the comments) to load your image properly. 阅读此示例 (请注意注释)以正确加载图像。

Try getClass().getResource("imgs/icon.png") . 尝试getClass().getResource("imgs/icon.png") It works for me. 这个对我有用。 Note the difference between absolute and relative path. 注意绝对路径和相对路径之间的差异。 You may not need the leading / . 你可能不需要领先/

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

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