日期:2014-05-20 浏览次数:20707 次
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; } }