To display an image in a JLabel in Java, you need to create an ImageIcon object that represents the image and set it as the icon of the label using the setIcon() method. Here is an example:
import javax.swing.*;
import java.awt.*;
public class LabelImageExample {
public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame("Label Image Example");
// Load an image from a file
ImageIcon icon = new ImageIcon("image.jpg");
// Create a new JLabel with the image icon
JLabel label = new JLabel(icon);
// Add the label to the frame
frame.add(label);
// Set the frame's size and make it visible
frame.setSize(300, 200);
frame.setVisible(true);
}
}
In the above example, the ImageIcon constructor is used to create an ImageIcon object that represents the image "image.jpg". Then, a new JLabel is created with the image icon using the JLabel(ImageIcon) constructor. Finally, the label is added to the frame and the frame is displayed.
Note that the path to the image file should be relative to the location of your Java file, or you can use an absolute path if needed. Additionally, make sure the image file is in a compatible format that can be loaded by ImageIcon, such as PNG, JPEG, or GIF.