Link 一条通向无处不在的 ImageIcon 的路径

Link a path to an ImageIcon that works everywhere

我最近在 JFrame 中编写程序。我正在使用 static ImageIcon img = new ImageIcon("X:/workspace/eclipse/Timer5/rsc/icon.png");f1.setIconImage(img.getImage()); 来显示 JFrame 的图标。我的问题是,如果程序导出为可运行的 jar,其他计算机上的路径将不再有效,图标显示标准 Java 图标。

因为我可以在我的标签 class 中指定这样的路径 logo = ImageIO.read(getClass().getResource("/logo.png")); g.drawImage(logo, 657, 640, 485, 85, null); (它扩展了 JLabel)并且它可以在其他计算机或移动的文件上工作,我想问一下如果这也适用于图像图标。如果我像使用 ImageIO.read() 一样输入路径,则不会加载任何图标。

I wanted to ask if this also works for image icons.

阅读 ImageIcon API。

您会发现一个以 Image 作为参数的构造函数。

所以是的,你可以而且应该使用 getResource() 方法:

Image image = ImageIO.read(...);
ImageIcon icon = new ImageIcon( image );
JLabel label = new JLabel( icon );