Display Image in Java Swing Application

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:

  1. Create a new JLabel object and load the image file using the ImageIcon class.
JLabel imageLabel = new JLabel(new ImageIcon("path/to/image.png"));
  1. Add the JLabel component to a container such as a JFrame or JPanel.
JFrame frame = new JFrame("My Application");
frame.getContentPane().add(imageLabel);
  1. Set the size and position of the JLabel within the container.
imageLabel.setBounds(0, 0, 200, 200);
  1. 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:

Display Image in Java Swing Application Display image in Java Swing

Sharing Is Caring: