Javaexercise.com

How to Add an Image to a JPanel in Swing

To add an image to JPanel, the Java Swing framework provides built-in classes such as ImageIO and ImageIcon that you can use to fetch an image.

Here, we will add an image to JLabel which will be added to JPanel. It is quite easy, let's see the example.

Add an Image to JPanel in Swing Java

The code below uses the read() method of ImageIO to fetch the image and then we pass it into the constructor of ImageIcon class which is eventually passed into JLabel.

import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/* 
 *  Code example to add an image into JPanel
 */
public class JExercise{

	public static void main(String[] args) throws IOException {
		JFrame f= new JFrame("Panel with image");    
		JPanel panel=new JPanel();  
		panel.setLayout(new FlowLayout());      
		BufferedImage myPicture = ImageIO.read(new File("Path/to/image/"));
		JLabel picLabel = new JLabel(new ImageIcon(myPicture));
		panel.add(picLabel);
		f.add(panel);
		f.setSize(500,500);            
		f.setVisible(true); 
	}
}

Output:

Image in Swing Jpanel

 

Add an Image to JPanel by using ImageIcon in Swing

If you want to avoid ImageIO class then simply use ImageIcon class as we do in the below code example. This class paints the icon of the specified image. 

import java.awt.FlowLayout;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/* 
 *  Code example to add an image into JPanel
 */
public class JExercise{

	public static void main(String[] args) throws IOException {
		JFrame f= new JFrame("Panel with image");    
		JPanel panel=new JPanel();  
		panel.setLayout(new FlowLayout());      
		JLabel picLabel = new JLabel(new ImageIcon("/Path/to/image"));
		panel.add(picLabel);
		f.add(panel);
		f.setSize(500,500);            
		f.setVisible(true); 
	}
}

Output:

Image in Swing JPanel

 

 

Also Read: How to close a JFrame Programmatically in Swing?