Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当使用字符串参数传递时,ImageIcon不显示图像_Java_Image_Swing_Jlabel_Imageicon - Fatal编程技术网

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

Java 当使用字符串参数传递时,ImageIcon不显示图像,java,image,swing,jlabel,imageicon,Java,Image,Swing,Jlabel,Imageicon,当我使用为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.createR

当我使用为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);

}
文件层次结构如下所示:

  • 项目名称
    • src
      • 标题板
    • 图像
  • 有人知道这会导致ImageIcon无法找到文件的原因吗

    public static String imageName = "\"images/q0.png\"";
    
    引号不应是文件名的一部分

    代码应为:

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

    这不仅适用于文件名,还适用于任何变量。您不需要将引号作为字符串的一部分。

    应用程序资源在部署时将成为嵌入式资源,因此现在就开始像访问一样访问它们是明智的。必须通过URL而不是文件访问。有关如何形成URL的信息,请参见。