java - 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.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";

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

关于java - ImageIcon 在传递字符串参数时不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322015/

相关文章:

javascript - jQuery 中的函数不返回变量

c# - 在 C# 中用文本更新图像后从数据库加载图像时参数无效

java - 从父类(super class)调用方法不起作用 Java

java - 行过滤器在单元格更新事件中无法按预期工作

java - Eclipse RCP 和 Apache CXF

java - 当 Wifi 状态发生变化(连接或断开网络)时如何触发 JobScheduler?

c++ - sf::Texture 作为类成员不起作用?

JPanel 中的 Java Linux 终端

c# - AES需要使用Java吗?

java - cvc-elt.1.a : Cannot find the declaration of element 'people'