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.swing;

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

public class JLabelWithIcon extends JFrame {
    public JLabelWithIcon() throws HeadlessException {

    private void initialize() {
        setSize(500, 500);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        Icon userIcon = new ImageIcon(
        JLabel userLabel = new JLabel("Full Name :", userIcon, JLabel.LEFT);

        final ImageIcon houseIcon = new ImageIcon(
        JLabel label2 = new JLabel("Address :", JLabel.LEFT);


    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new JLabelWithIcon().setVisible(true));
JLabel witch Image Icon

JLabel witch Image Icon


  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.

  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.

    • That’s exactly what I did. I tried it in multiple ways and luckily I found one that’s working. I just can’t see any difference in logic (if you know what I mean, sorry for my bad english, I’m german).

      So the one working is this one:

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

Leave a Reply to Wayan Saryada Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.