public ImageViewerFrame() {
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    // set up menu bar
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu menu = new JMenu("File");
    menuBar.add(menu);

    JMenuItem openItem = new JMenuItem("Open");
    menu.add(openItem);
    openItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            chooser.setCurrentDirectory(new File("."));

            // show file chooser dialog
            int result = chooser.showOpenDialog(ImageViewerFrame.this);

            // if image file accepted, set it as icon of the label
            if (result == JFileChooser.APPROVE_OPTION) {
              String name = chooser.getSelectedFile().getPath();
              label.setIcon(new ImageIcon(name));
              pack();
            }
          }
        });

    JMenuItem exitItem = new JMenuItem("Exit");
    menu.add(exitItem);
    exitItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            System.exit(0);
          }
        });

    // use a label to display the images
    label = new JLabel();
    add(label);

    // set up file chooser
    chooser = new JFileChooser();

    // accept all image files ending with .jpg, .jpeg, .gif
    /*
    final ExtensionFileFilter filter = new ExtensionFileFilter();
    filter.addExtension("jpg");
    filter.addExtension("jpeg");
    filter.addExtension("gif");
    filter.setDescription("Image files");
    */
    FileNameExtensionFilter filter =
        new FileNameExtensionFilter("Image files", "jpg", "jpeg", "gif");
    chooser.setFileFilter(filter);

    chooser.setAccessory(new ImagePreviewer(chooser));

    chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
  }
Пример #2
0
 /** register for events from the specified file chooser */
 public void applyTo(final JFileChooser fileChooser) {
   fileChooser.setAccessory(new AccessoryView().getComponent());
   applyDefaultFolder(fileChooser);
   fileChooser.addPropertyChangeListener(this);
 }