当我使用为 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);
}
文件层次结构如下:
- 项目名称
- 源代码
- 标题面板
- 图片
- 源代码
有谁知道为什么这会导致 ImageIcon 找不到该文件?
最佳答案
public static String imageName = "\"images/q0.png\"";
引号不应成为文件名的一部分。
代码应该是:
public static String imageName = "images/q0.png";
这不仅适用于文件名,也适用于任何变量。您不包括引号作为字符串的一部分。
关于java - ImageIcon 在传递字符串参数时不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322015/