使用字符串参数传递时,ImageIcon 不显示图像

ImageIcon does not display image when passed with a string parameter

当我使用为 ImageIcon 写入的文件名设置面板时,它工作正常:

public TitlePanel(){
    setOpaque(false);
    setLayout(new BoxLayout( this, BoxLayout.Y_AXIS ));

    ImageIcon image = new ImageIcon("images/q0.png");
    JLabel imageLabel = new JLabel( image);
    add(Box.createRigidArea(new Dimension(150,40)));
    add(imageLabel);
}

但是,当我向 ImageIcon 传递一个字符串时,它停止工作并且没有任何错误消息。图像只是没有出现,但它打印出正确的字符串路径:

public static String imageName = "\"images/q0.png\"";

public TitlePanel(){
    setOpaque(false);
    setLayout(new BoxLayout( this, BoxLayout.Y_AXIS ));

    ImageIcon image = new ImageIcon(imageName);
    System.out.println(imageName);
    JLabel imageLabel = new JLabel( image);
    add(Box.createRigidArea(new Dimension(150,40)));
    add(imageLabel);

}

文件层级如下:

  1. 项目名称
    • 来源
      • 标题面板
    • 图片

有谁知道为什么这会导致 ImageIcon 找不到文件?

public static String imageName = "\"images/q0.png\"";

引号不应是文件名的一部分。

代码应该是:

public static String imageName = "images/q0.png";

这不仅适用于文件名,它适用于任何变量。您没有将引号包含在字符串中。