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. In this article, we will learn to display image in Java Swing Application.

1. Create JLabel Component

Create a new JLabel object and load the image file using the ImageIcon class.

    JLabel imageLabel = new JLabel(new ImageIcon("path/to/image.png"));

    2. Add JLabel to Container

    Add the JLabel component to a container such as a JFrame or JPanel.

      JFrame frame = new JFrame("My Application");
      frame.getContentPane().add(imageLabel);

      3. Set JLabel Size

      Set the size and position of the JLabel within the container.

        imageLabel.setBounds(0, 0, 200, 200);

        4. Make Container Visible

        Make the container visible.

          frame.setVisible(true);

          5. Complete Example Code

          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);
          	}
          }

          6. Output

          The output of the above code is:

          Display Image in Java Swing Application

          Sharing Is Caring: