【问题标题】:Cannot display image with correct path using ImageIcon无法使用 ImageIcon 显示具有正确路径的图像
【发布时间】:2016-05-04 15:50:47
【问题描述】:

我在使用 ImageIcon 类在 Java 中显示图像时遇到了问题。代码很简单,不过只是显示了一个类似

的窗口

.

 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"

程序正常运行。

我们将不胜感激。

谢谢!

【问题讨论】:

    标签: java image swing user-interface icons


    【解决方案1】:

    ImageIcon(String) 假定图像位于磁盘上的某个位置。当您将图像放在src 目录中时,大多数 IDE 会将图像捆绑到生成的 Jar(AKA 嵌入式资源)中,这意味着它们不再是磁盘上的“文件”,而是 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了解更多详情

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        问题在于图像的位置。将您的图像放在源文件夹中。试试看

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

        我假设图片在src/images

        【讨论】:

          【解决方案4】:

          你给 ImageIcon 的构造函数的路径是相对于你的类的位置的。 所以如果你的类是 org.example.TestButtonIcons 它会寻找 org/example/images/usFlag.png

          希望这会有所帮助。

          【讨论】:

            猜你喜欢
            • 2022-12-07
            • 2019-11-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-10-25
            相关资源
            最近更新 更多