Hi maheswari
Java Provides builtin classes Observer and Observable to achieve this functionality.AWT/Swing event model uses ObserverPattern to large extend especially in event handling.
I am sending code,
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.Serializable;
public class ObserverTest extends JFrame{
private DefaultBoundedRangeModel rangeModel = new DefaultBoundedRangeModel(100,0,0,100);
private JSlider slider = new JSlider(rangeModel);
private JLabel lable = new JLabel("100%");
private ImageIcon image = new ImageIcon("cat.gif");
private ImageView imageView = new ImageView(image,rangeModel);
public ObserverTest(){
super("Observer example frame");
Container contentPane = getContentPane();
JPanel panel = new JPanel();
panel.add(new JLabel("Set Image Size:"));
panel.add(slider);
panel.add(lable);
contentPane.add(panel, BorderLayout.NORTH);
contentPane.add(imageView, BorderLayout.CENTER);
rangeModel.addChangeListener(new ReadOutSynchronizer());
}
public static void main(String args[]) {
System.out.println("Display frame with image.");
ObserverTest otest = new ObserverTest();
otest.setBounds(100,100,400,350);
otest.setSize(400,400);
otest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
otest.setVisible(true);
}
class ReadOutSynchronizer implements ChangeListener {
public void stateChanged(ChangeEvent e) {
String s = Integer.toString(rangeModel.getValue());
lable.setText(s + "%");
lable.revalidate();
}
}
}
class ImageView extends JScrollPane {
private JPanel panel = new JPanel();
private Dimension originalSize = new Dimension();
private Image originalImage;
private ImageIcon icon;
public ImageView(ImageIcon icon, BoundedRangeModel rangeModel) {
panel.setLayout(new BorderLayout());
panel.add(new JLabel(icon));
this.icon = icon;
this.originalImage = icon.getImage();
setViewportView(panel);
rangeModel.addChangeListener(new ModelListener());
originalSize.width = icon.getIconWidth();
originalSize.height = icon.getIconHeight();
}
class ModelListener implements ChangeListener {
public void stateChanged(ChangeEvent e){
BoundedRangeModel model = (BoundedRangeModel)e.getSource();
if(model.getValueIsAdjusting()) {
int min = model.getMinimum(), max = model.getMaximum(), span = max - min, value = model.getValue();
double multiplier = (double)value / (double)span;
multiplier = multiplier == 0.0 ? 0.01 : multiplier;
Image scaled = originalImage.getScaledInstance((int)(originalSize.width * multiplier),
(int)(originalSize.height * multiplier), Image.SCALE_FAST);
icon.setImage(scaled);
panel.revalidate();
panel.repaint();
}
}
}
}
---------------------------------------
read for more information.
http://www.roseindia.net/java/