27
Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
KJW
  • 15,035
  • 47
  • 137
  • 243

5 Answers5

36

You have to supply to the JLabel an Icon implementation (i.e ImageIcon). You can do it trough the setIcon method, as in your question, or through the JLabel constructor:

Image image=GenerateImage.toImage(true);  //this generates an image file
ImageIcon icon = new ImageIcon(image); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

I recommend you to read the Javadoc for JLabel, Icon, and ImageIcon. Also, you can check the How to Use Labels Tutorial, for more information.

Tomas Narros
  • 13,390
  • 2
  • 40
  • 56
25

To get an image from a URL we can use the following code:

ImageIcon imgThisImg = new ImageIcon(PicURL));

jLabel2.setIcon(imgThisImg);

It totally works for me. The PicUrl is a string variable which strores the url of the picture.

Nitesh Verma
  • 1,795
  • 4
  • 27
  • 46
12

(If you are using NetBeans IDE) Just create a folder in your project but out side of src folder. Named the folder Images. And then put the image into the Images folder and write code below.

// Import ImageIcon     
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);

Now run your program.

mezba z
  • 137
  • 1
  • 10
4

the shortest code is :

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is PATH of image .

Adnan Abdollah Zaki
  • 4,328
  • 6
  • 52
  • 58
1

Simple code that you can write in main(String[] args) function

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//application will be closed when you close frame
    frame.setSize(800,600);
    frame.setLocation(200,200);

    JFileChooser fc = new JFileChooser();
    if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
        BufferedImage img = ImageIO.read(fc.getSelectedFile());//it must be an image file, otherwise you'll get an exception
        JLabel label = new JLabel();
        label.setIcon(new ImageIcon(img));
        frame.getContentPane().add(label);
    }

    frame.setVisible(true);//showing up the frame
alexlz
  • 618
  • 1
  • 10
  • 24