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 {
initialize();
}
private void initialize() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
Icon userIcon = new ImageIcon(
Objects.requireNonNull(this.getClass().getResource("/images/user.png")));
JLabel userLabel = new JLabel("Full Name :", userIcon, JLabel.LEFT);
final ImageIcon houseIcon = new ImageIcon(
Objects.requireNonNull(this.getClass().getResource("/images/house.png")));
JLabel label2 = new JLabel("Address :", JLabel.LEFT);
label2.setIcon(houseIcon);
getContentPane().add(userLabel);
getContentPane().add(label2);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new JLabelWithIcon().setVisible(true));
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
How come I get a
NullPointerException
when I try it like that?Because I have no clue why.
It seems like that it cannot load the
MyPic.png
. Modify your code into something like this: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:
You should read the Javadoc of the
Class.getResource()
method, it might give you a better understanding. Here is the link to the Javadoc.Please, put the example like a Maven Project, with
src/main/resources
folder.