To display an image in a Java Swing application, we can use the JLabel
component to hold the image and add it to a container, such as a JFrame
or JPanel
.
Following are the steps we can follow:
- Create a new
JLabel
object and load the image file using theImageIcon
class.
JLabel imageLabel = new JLabel(new ImageIcon("path/to/image.png"));
- Add the
JLabel
component to a container such as aJFrame
orJPanel
.
JFrame frame = new JFrame("My Application"); frame.getContentPane().add(imageLabel);
- Set the size and position of the
JLabel
within the container.
imageLabel.setBounds(0, 0, 200, 200);
- Make the container visible.
frame.setVisible(true);
Following is an example code that displays the image in a JFrame.
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ImageDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Image Display Example");
frame.setSize(700, 500);
JLabel imageLabel = new JLabel(new ImageIcon("C:\\Users\\codersathi\\Downloads\\LogoWithText.png"));
imageLabel.setBounds(0, 0, 400, 400);
frame.add(imageLabel);
frame.setVisible(true);
}
}
The output of the above code is: