Java 当使用字符串参数传递时,ImageIcon不显示图像
当我使用为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
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
- 标题板
- 图像
public static String imageName = "\"images/q0.png\"";
引号不应是文件名的一部分
代码应为:
public static String imageName = "images/q0.png";
这不仅适用于文件名,还适用于任何变量。您不需要将引号作为字符串的一部分。应用程序资源在部署时将成为嵌入式资源,因此现在就开始像访问一样访问它们是明智的。必须通过URL而不是文件访问。有关如何形成URL的信息,请参见。