import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.beans.*;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;
public class FileChooserTest
{
public static void main(String[] args )
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
ImageViewerFrame frame = new ImageViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class ImageViewerFrame extends JFrame
{
public ImageViewerFrame()
{
setTitle("FileChooserTest");
setSize(300, 400);
JMenuBar mbar= new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu= new JMenu("File");
mbar.add(fileMenu);
JMenuItem openItem = new JMenuItem("Open");
fileMenu.add(openItem);
openItem.addActionListener(new FileOpenListener());
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(exitItem);
exitItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
label = new JLabel();
add(label);
chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files","jpg","jpeg","gif");
chooser.setFileFilter(filter);
chooser.setAccessory(new ImagePreviewer(chooser));
chooser.setFileView(new FileIconView(filter,new ImageIcon("paletee.gif")));
}
private JLabel label;
private JFileChooser chooser=null;
private class FileOpenListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
chooser.setCurrentDirectory(new File("."));
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(ImageViewerFrame.this);
if (result == JFileChooser.APPROVE_OPTION)
{
String filename= chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(filename));
}
}
private JLabel label;
private Component ImageViewerFrame;
}
}
class FileIconView extends FileView
{
public FileIconView(FileFilter aFilter, Icon anIcon)
{
filter= aFilter;
icon= anIcon;
}
public Icon getIcon(File f)
{
if (!f.isDirectory()&& filter.accept(f)) return icon;
else return null;
}
private FileFilter filter;
private Icon icon;
}
class ImagePreviewer extends JLabel
{
public ImagePreviewer(JFileChooser chooser)
{
setPreferredSize(new Dimension(100,100));
setBorder(BorderFactory.createEtchedBorder());
chooser.addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent event)
{
if (event.getPropertyName()== JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
{
File f = (File) event.getNewValue();
if (f== null)
{
setIcon(null);
return;