[Solved] Put Image inside JPanel

I found many people asking for this code in internet. So, I have written a code for myself as well. I know this code might not be the optimized one, but it works for me and hope works for my friends too. To put image inside JPanel we have to paint the JPanel. And I have written my actual code inside paint method of JPanel.

Source Code :

/**
 * 
 */
// package mts;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @author Asee Shrestha
 *
 */
public class DrawToPanel {
	static double SCALE_FACTOR = 2;
	static int WINDOW_WIDTH = 640;
	static int WINDOW_HEIGHT = 480;
	
	//** Change this path to the image location on your harddisk **/
	String imagePath = "f:\\test1.jpg";
	
	DrawToPanel(String title) 
	{
		Dimension size = new Dimension(WINDOW_WIDTH,WINDOW_HEIGHT);
		
		JFrame window = new JFrame();
		window.setTitle(title);
		
		DrawPanel drawingPanel = new DrawPanel();
		JPanel buttons = new JPanel();
		buttons.setLayout(new FlowLayout(FlowLayout.LEFT));
		drawingPanel.setPreferredSize(size);
		
		JButton btnOk = new JButton(" OK ");
		JButton btnCancel = new JButton(" Cancel ");
				
		window.add(drawingPanel,BorderLayout.NORTH);
		buttons.add(btnOk);
		buttons.add(btnCancel);
		window.add(buttons);
		
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		window.pack();
		window.setVisible(true);
		
	}	

	
	class DrawPanel extends JPanel {
		
		/** This paint method actually puts the image inside JPanel **/
		public void paint(Graphics g) {
			Graphics2D g2d = (Graphics2D)g;
			try {
				BufferedImage bi = ImageIO.read(new File(imagePath));
				g2d.drawImage(bi, 0, 0, (int)(320*SCALE_FACTOR), (int)(240*SCALE_FACTOR), Color.RED, null);
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}
	public static void main(String[] args) {
		DrawToPanel d = new DrawToPanel("Demo Image Inside JPanel");
	
	}

}

The two buttons Ok and Cancel doesn’t work, because I haven’t written any code for them, I just put it their, if someone needs, that . You have to write your own action handling code for them.
If you have any difficulty in using this code let me know, drop comments, I will try to help you as soon as possible.

Do not use this code, in your production software, since this might not be the secure one. I take no responsibility if something goes wrong by using this code in your software.

otherwise,
best regards,
Asee

One thought on “[Solved] Put Image inside JPanel

Leave a Reply

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