【问题标题】:ImageIcon does not display image when passed with a string parameterImageIcon 使用字符串参数传递时不显示图像
【发布时间】:2015-09-01 00:55:49
【问题描述】:

当我使用为 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 无法找到该文件?

【问题讨论】:

标签: java image swing jlabel imageicon


【解决方案1】:
public static String imageName = "\"images/q0.png\"";

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

代码应该是:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-12
    • 2014-06-04
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2018-08-05
    相关资源
    最近更新 更多