Java Swing GUI

How to Add an Image to a JPanel in Java Swing

In this tutorial, we are going to see how to add an image to a JPanel in Java Swing. In the following example we have used this image, you can upload it to your project.


 

Java Program to Add an Image to a JPanel:
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;


public class ImagePanel 
{
 ImagePanel() 
 {
  try 
  {
   JFrame f = new JFrame("Add an Image to a JPanel");
   JPanel panel = new JPanel();
   panel.setBounds(50, 50, 250, 250);

   BufferedImage img = ImageIO.read(new File("test.png"));
   JLabel pic = new JLabel(new ImageIcon(img));
   panel.add(pic);

   f.add(panel);
   f.setSize(400, 400);
   f.setLayout(null);
   f.setVisible(true);
  } 
  catch (IOException e) {}
 }
 public static void main(String args[]) 
 {
  new ImagePanel();
 }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *