Sunday, March 16, 2014

How to change image on JPanel on action Command button

Welcome to itsitrc blogspot .

This article is for Java Applet .


Problem :



How to change image on JPanel on action Command button ?


Answer :



To satisfy this output we have step by step code described below.
To carry out this code you need to save images in your bin folder inside your workspace and just for example you need have .jpg extension images.
Save it as :
"1.jpg ",  "2jpg" ... so on just for testing issue....!



OUTPUT : 



Once you get the logic you can implement it by your own logic. Now follow the Below instruction and try it your self.Just remember the sequence and save images as stated above and check the Extension,it should be same for all images.


// Necessary packages need to be imported are listed below : 

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;



public class ImageChange extends JApplet implements ActionListener {

        /*Here we're using 2 JPanels in 1 container ,where 1st JPanel will contain the JLabel which will contain the image inside it and another JPanel will contain button. */
      
        JPanel p1=new JPanel();
JPanel p2=new JPanel();

       // Button for performing action after click.

       JButton b1=new JButton("Change IMAGE");

        //counter set for increasing name of image
        int count=1;

        JLabel img=new JLabel();


        /* Saving name of Image i.e. count is the name we are taking and in double quotes we're giving                        extension of that particular file.*/
        String image_name=count+".jpg";

//Creating object of container on which we will add JPanels.
        Container c1=getContentPane();
public void init()
{
//setting size for applet
setSize(600,600);

                //adding listner for button so to have results after click on button
b1.addActionListener(this);
//adding JLabel with image on JPanel 1
                p1.add(img);
//adding Button on 2nd JPanel
                p2.add(b1);
p2.setBackground(Color.red);
//Setting size for JPanel
                p1.setPreferredSize(new Dimension(600,500));
//Setting Layout for Container for adding different components
                c1.setLayout(new FlowLayout());
c1.setBackground(Color.black);
c1.add(p1);
c1.add(p2);



}
public void paint(Graphics g)
{
String s2="IMAGE CHANGING APP";
super.paint(g);
g.drawString(s2, 400, 500);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
++count;
image_name=count+".jpg";
//using object of JLabel and adding a image with changing value of image name i.e. count
                        img.setIcon(new ImageIcon(image_name));
repaint();
}
}
}

Download CODE :


Download Images for Practice :



Extract this folder in your bin folder of project of java.