为我的Java应用程序设置图标

我正处于代码/应用程序的中间,我已经到了公开发布它的地步。 我想知道一个简单的示例代码,说明如何为应用程序“设置”ICON图像。 只是一个简单的代码,我可以放在我的类的顶部,将从其目录中抓取Icon图像[/res/Icon.png]

谢谢<3

你可以使用Frame#setIconImage(Image)或者你想要一些更灵活的东西, Window#setIconImages(List)

如所示

  • 在Java中设置图标图像
  • 如何将图像添加到JFrame标题栏?

请相信这些作者

更新了简单的示例

按照它的性质加载图像会引发问题。 你需要为它可能失败的事实做好准备。 希望你已经准备好了应用程序,在正常操作下,这将是一种罕见的情况

 import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Image; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class FrameIconTest { public static void main(String[] args) { new FrameIconTest(); } public FrameIconTest() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Testing"); try { List icons = new ArrayList(5); icons.add(ImageIO.read(getClass().getResource("/resources/FrameIcon16x16.png"))); icons.add(ImageIO.read(getClass().getResource("/resources/FrameIcon24x24.png"))); icons.add(ImageIO.read(getClass().getResource("/resources/FrameIcon32x32.png"))); icons.add(ImageIO.read(getClass().getResource("/resources/FrameIcon64x64.png"))); icons.add(ImageIO.read(getClass().getResource("/resources/FrameIcon128x128.png"))); frame.setIconImages(icons); } catch (IOException exp) { exp.printStackTrace(); // Log the problem through your applications logger... } frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new JLabel("Frame with icon")); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }