无法使用 ImageIcon 显示具有正确路径的图像

Cannot display image with correct path using ImageIcon

我一直在使用 ImageIcon class 在 Java 中显示图像时遇到问题。代码很简单,只是简单的显示了一个window like

.

 import javax.swing.*;
 public class TestButtonIcons {
    public static void main(String[] args) {
        ImageIcon usFlag = new ImageIcon("images/usFlag.png");
        JFrame frame = new JFrame();
        JButton jbt = new JButton(usFlag);
        frame.add(jbt);
        frame.setSize(500, 500);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

我的图片在src文件夹下,我的IDE也能检测到,因为显示

.

另外,如果我把上面提到的路径改成完整路径,比如

"/Users/Mac/Documents/Java TB/ImageIcons/src/images/usFlag.png"

程序运行正常。

任何帮助将不胜感激。

谢谢!

确保使用“./path”,否则它可能会认为这是绝对路径。 “。”是当前目录,是相对路径,不是绝对路径。

问题出在图像的位置。将图像放在源文件夹中。点赞

  JButton button = new JButton();
  try {
    Image img = ImageIO.read(getClass().getResource("images/usFlag.png"));
    button.setIcon(new ImageIcon(img));
  } catch (IOException ex) {
  }

我假设图像在 src/images

您为 ImageIcon 的构造函数提供的路径是相对于您 class 的位置的。 因此,如果您的 class 是 org.example.TestButtonIcons,它将查找 org/example/images/usFlag.png

希望对您有所帮助。

ImageIcon(String) 假定图像位于磁盘上的某处。当您将图像放入 src 目录时,大多数 IDE 会将图像捆绑到生成的 Jar(也称为嵌入式资源)中,这意味着它们不再是 "file"磁盘,而是 zip 文件中的字节流,因此您需要以不同的方式访问它们。

从使用ImageIO.read开始,不像ImageIcon,它会在无法加载图像时抛出IOException

您需要使用 Class#getResourceClass#getResourceAsStream 取决于需要如何引用它,例如...

BufferedImage image = null;
try {
    image = ImageIO.read(getClass().getResource("/images/usFlag.png"));
} catch (IOException ex) {
    ex.printStackTrace();
}

查看 Reading/Loading an Image 了解更多详情