Search code examples
javaswingiconsjlabelimageicon

Using an ImageIcon and a JLabel


My goal is to have an imageIcon and add it so a JLabel so it will appear on my GUI. So far my code is:

package classes;

import javax.swing.*;

public class Picture extends JFrame {

    private ImageIcon _image1;
    private JLabel _mainLabel;      

    public Picture(){           
        _image1 = new ImageIcon("picture1.jpg");
        _mainLabel = new JLabel(_image1);
        add(_mainLabel);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }    
}    

package classes;

public class Driver {    
    public static void main(String[] args) {
        Picture p = new Picture();    
    }    
}

The problem is the picture does not appear on my GUI. If anyone has any suggestions please let me know thanks!


Solution

  • Are you sure that Java is looking in the right location for your picture1.jpg file? Is this file located in the current working directory?

    Put this code somewhere in your program so that it gets called when the program is run:

    // show the current working directory
    System.out.println("current working directory is: " + System.getProperty("user.dir")); 
    

    The String returned will tell you where Java is looking, where your current working directory is located. You can then use that information to adjust your path or you could always just use the full path to the image file.

    Edit:
    Also, don't forget to pack your JFrame so that it will layout the components and size itself accordingly:

       public Picture() {
    
          _image1 = new ImageIcon(IMAGE);
          _mainLabel = new JLabel(_image1);
          add(_mainLabel);
    
          pack(); // to tell the layout managers to set up the GUI
          setLocationRelativeTo(null); // center things
          setVisible(true);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       }