Tuesday, March 11, 2014

How to set Image to JPanel in java

How to set image in JPanel or Panel in java Applet using Eclipse

For carrying out the most simplest way to add image in a JPanel in java applet follow the below steps :

1.Save the Image in bin folder, where your Project is stored in Workspace.

2.Confirm and check the exact type of Image file for Example it can be .jpg or .jpeg or so on...

3.Open your notepad or if you're using java eclipse or any other java working environment.

4.You need to include basic two packages i.e."  java.awt.*;  " and " javax.swing.*; ".

5.extend the JApplet class to get the GUI.

6.You need to declare, initialize and add JLabel. Here JLabel will contain image and this JLabel will be added to a JPanel. Now here JPanel is initialized and added to a container , which is on JApplet.

//Packages need to import i.e. need to include

import java.awt.*;
import javax.swing.*;

//class that include JApplet

public class ImagePanel extends JApplet {
//Declare JLabel variable , on which Image will be added
            JLabel image1;
 //JPanel Declaration .
            JPanel p1;        
 //Container Initialization
            Container c1=getContentPane();        

//Method of JApplet where initialization of JApplet takes place.
            public void init()
                        setSize(500,300); //Setting size of JApplet
 //Initialization of JLabel variable image1
                        image1=new JLabel();       
//Now most Important line. This is a method of Image class i.e. ImageIcon , //which sets the Image but taking the path of image with it's name. Here "1.jpg" //is the image's name and it is saved in bin folder where the .class file of our //program is created.
//Now to set Image use the Variable of initialized variable of JLabel and call the
//setIcon to set the Image Icon.

                        image1.setIcon(new ImageIcon("1.jpg"));
                        p1=new JPanel();                //JPanel Initialization
                        p1.setPreferredSize(new Dimension(300,300));        //Size for JPanel
                        p1.add(image1);     //adding JLabel with image on JPanel
                        c1.add(p1);               //adding JPanel on Container
                        repaint();                  //Calling Repaint() method
            public void paint(Graphics g)



Download Code :