Search code examples
javaswingloadimage

How to pass a file location as a parameter as a string?


Currently I pass a hardcoded string file location to my object method which uses the string in the .getResources() method to load an image file. I am now trying to chooses an image using a load button and pass the loaded file location as a string into the getResource() method. I am using the filename.getAbsolutePath() method to retrieve the file location then passing the filename variable into the object method however this provides me with the following error - Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException. The line of code that it points to having the error is the .getResources line where the image is loaded. I will post the code below to better understand my problem.

btnLoad.addActionListener(new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent e) {


                 JFileChooser fc = new JFileChooser();
                 if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
                 {
                    File loadImage = fc.getSelectedFile();
                    String filename = loadImage.getAbsolutePath();
                    filename = filename.replaceAll("\\\\", "\\\\\\\\");
                    picLocation = filename;
                    ImageSwing imageSwing = new ImageSwing(filename);
                    System.out.println(filename);
                 }
              }

The output of the file name is correct yet it still wont pass into the object.

  public class ImageSwing extends JFrame
  {
  public JLabel label;

  public ImageSwing(String S){

  super("Card Stunt");                //Window Title
  setLayout(new FlowLayout());        //lookup grid layout


  Icon flag = new ImageIcon(getClass().getResource(S));          
  label = new JLabel(flag);
  label.setToolTipText(S);
  setSize(1350, 800);
  //setMinimumSize(new Dimension(1200, 760));

  }//main
 }

Solution

  • It seems like you create an absolute filename with loadImage.getAbsolutePath(), but then you try to use this as a class path resource with new ImageIcon(getClass().getResource(S)).

    Instead, you should just pass the absolute filename, as a string, to ImageIcon:

    Icon flag = new ImageIcon(S);
    

    Also, don't forget to add the label to the frame...

    getContentPane().add(label);
    

    Also, I'm not on Windows right now, but I don't think filename.replaceAll("\\\\", "\\\\\\\\"); is necessary.