如何将Icon设置为JFrame

vij*_*jay 23 java icons swing jframe

我试过这种方式,但它没有改变?

ImageIcon icon = new ImageIcon("C:\\Documents and Settings\\Desktop\\favicon(1).ico");
frame.setIconImage(icon.getImage());
Run Code Online (Sandbox Code Playgroud)

Joo*_*gen 38

更好地使用.png文件; .ico是Windows特定的.最好不要使用文件,而是使用类资源(可以打包在应用程序的jar中).

URL iconURL = getClass().getResource("/some/package/favicon.png");
// iconURL is null when not found
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());
Run Code Online (Sandbox Code Playgroud)

虽然您甚至可能会考虑将setIconImages用于多种尺寸的图标.

  • 即使图像路径正确,我也一直收到空指针异常 (2认同)
  • 迟到的响应:图标应该与您调用getClass()的类位于同一个jar中,并且路径使用`/`区分大小写. (2认同)

小智 6

尝试将图像放在src文件夹之外的单独文件夹中.然后,使用ImageIO加载图像.它应该如下所示:

frame.setIconImage(ImageIO.read(new File("res/icon.png")));
Run Code Online (Sandbox Code Playgroud)