Search code examples
javaimageswingjlabelimageicon

ImageIcon does not display image when passed with a string parameter


When I set up the panel with the filename written in for the ImageIcon it works fine:

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);
}

However when I pass the ImageIcon a string, it stops working with no error message. The image just does not come up, but it prints out the right string path:

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);

}

The file hierarchy is as follows:

  1. projectName
    • src
      • TitlePanel
    • images

Does anyone know why this would cause ImageIcon to not be able to find the file?


Solution

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

    Quotes should not be part of the filename.

    The code should be:

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

    This is not just for filenames, it is for any variable. You don't include the quotes as part of the string.