How do I create JLabel with an image icon?

To create a JLabel with an image icon we can either pass an ImageIcon as a second parameter to the JLabel constructor or use the JLabel.setIcon() method to set the icon.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class JLabelWithIcon extends JFrame {
    public JLabelWithIcon() throws HeadlessException {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        Icon icon = new ImageIcon("ledgreen.png");
        JLabel label1 = new JLabel("Full Name :", icon, JLabel.LEFT);

        JLabel label2 = new JLabel("Address :", JLabel.LEFT);
        label2.setIcon(new ImageIcon("ledyellow.png"));

        getContentPane().add(label1);
        getContentPane().add(label2);        
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JLabelWithIcon().setVisible(true);
            }
        });
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

4 Comments

  1. How come I get a NullPointerException when I try it like that?

    JLabel label = new JLabel();
    label.setIcon(new ImageIcon(getClass().getResource("MyPic.png")));
    

    Because I have no clue why…

    Reply
  2. It seems like that it cannot load the MyPic.png. Modify your code into something like this:

    label.setIcon(new ImageIcon(getClass().getResource("/MyPic.png")));
    

    and place the image file in the root directory of your classes.

    Reply

Leave a Reply