19 May 2011

Image Preview In JFileChooser


 Image Preview In JFileChooser

Hello Friends,
Nice to meet you again.

Today we will learn Image Priview In JFileChooser.
here I am giving simple example that will help you to learn to apply Image Priview Facility In JFileChooser.

The output will be:



Now create one class ImagePreviewFileChooser.java and pate the below code in it and run it.
-----------------------------------------------------------------------------------------------------------------------------------


import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImagePreviewFileChooser extends JPanel implements PropertyChangeListener {
private JFileChooser jfc;
private Image img;

public ImagePreviewFileChooser(JFileChooser jfc) {
this.jfc = jfc;
Dimension sz = new Dimension(200, 200);
setPreferredSize(sz);
}

public void propertyChange(PropertyChangeEvent evt) {
try {
System.out.println("updating");
File file = jfc.getSelectedFile();
updateImage(file);
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}

public void updateImage(File file) throws IOException {
if (file == null) {
return;
}
img = ImageIO.read(file);
repaint();
}

public void paintComponent(Graphics g) {
// fill the background
g.setColor(Color.gray);
g.fillRect(0, 0, getWidth(), getHeight());

if (img != null) {
// calculate the scaling factor
int w = img.getWidth(null);
int h = img.getHeight(null);
int side = Math.max(w, h);
double scale = 200.0 / (double) side;
w = (int) (scale * (double) w);
h = (int) (scale * (double) h);
// draw the image
g.drawImage(img, 0, 0, w, h, null);

// draw the image dimensions
String dim = w + " x " + h;
g.setColor(Color.black);
g.drawString(dim, 31, 196);
g.setColor(Color.white);
g.drawString(dim, 30, 195);
} else {
// print a message
g.setColor(Color.black);
g.drawString("Not an image", 30, 100);
}
}

public static void main(String[] args) {
JFileChooser jfc = new JFileChooser();
ImagePreviewFileChooser preview = new ImagePreviewFileChooser(jfc);
jfc.addPropertyChangeListener(preview);
jfc.setAccessory(preview);
jfc.showOpenDialog(null);
}

}
------------------------------------------------------------------------------------------------------------------------------------

Here I am using one Panel in JFilechooser which displays selected Image File.
Every time user selects Image File that Image will be painted on that Panel with paintComponent method.

-----------------------------------------------------------------------------------------------------------------------------------

Try this code and feel free to ask any dought or give any suggessions.
I always invite your valuable suggessions.

Thank you.
Nirav Raval

No comments:

Post a Comment

Leave Comment If You Like This...Thank You..!