Path: blob/master/src/demo/share/jfc/SwingSet2/FileChooserDemo.java
41149 views
/*1*2* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7*8* - Redistributions of source code must retain the above copyright9* notice, this list of conditions and the following disclaimer.10*11* - Redistributions in binary form must reproduce the above copyright12* notice, this list of conditions and the following disclaimer in the13* documentation and/or other materials provided with the distribution.14*15* - Neither the name of Oracle nor the names of its16* contributors may be used to endorse or promote products derived17* from this software without specific prior written permission.18*19* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS20* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,21* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR22* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR23* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,24* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,25* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR26* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF27* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING28* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS29* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.30*/313233import javax.swing.*;34import javax.swing.event.*;35import javax.swing.text.*;36import javax.swing.border.*;37import javax.swing.colorchooser.*;38import javax.swing.filechooser.*;39import javax.accessibility.*;4041import java.awt.*;42import java.awt.event.*;43import java.beans.*;44import java.util.*;45import java.io.*;46import java.applet.*;47import java.net.*;4849/**50* JFileChooserDemo51*52* @author Jeff Dinkins53*/54public class FileChooserDemo extends DemoModule {55JLabel theImage;56Icon jpgIcon;57Icon gifIcon;5859/**60* main method allows us to run as a standalone demo.61*/62public static void main(String[] args) {63FileChooserDemo demo = new FileChooserDemo(null);64demo.mainImpl();65}6667/**68* FileChooserDemo Constructor69*/70public FileChooserDemo(SwingSet2 swingset) {71// Set the title for this demo, and an icon used to represent this72// demo inside the SwingSet2 app.73super(swingset, "FileChooserDemo", "toolbar/JFileChooser.gif");74createFileChooserDemo();75}7677public void createFileChooserDemo() {78theImage = new JLabel("");79jpgIcon = createImageIcon("filechooser/jpgIcon.jpg", "jpg image");80gifIcon = createImageIcon("filechooser/gifIcon.gif", "gif image");8182JPanel demoPanel = getDemoPanel();83demoPanel.setLayout(new BoxLayout(demoPanel, BoxLayout.Y_AXIS));8485JPanel innerPanel = new JPanel();86innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS));8788demoPanel.add(Box.createRigidArea(VGAP20));89demoPanel.add(innerPanel);90demoPanel.add(Box.createRigidArea(VGAP20));9192innerPanel.add(Box.createRigidArea(HGAP20));9394// Create a panel to hold buttons95JPanel buttonPanel = new JPanel() {96public Dimension getMaximumSize() {97return new Dimension(getPreferredSize().width, super.getMaximumSize().height);98}99};100buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));101102buttonPanel.add(Box.createRigidArea(VGAP15));103buttonPanel.add(createPlainFileChooserButton());104buttonPanel.add(Box.createRigidArea(VGAP15));105buttonPanel.add(createPreviewFileChooserButton());106buttonPanel.add(Box.createRigidArea(VGAP15));107buttonPanel.add(createCustomFileChooserButton());108buttonPanel.add(Box.createVerticalGlue());109110// Create a panel to hold the image111JPanel imagePanel = new JPanel();112imagePanel.setLayout(new BorderLayout());113imagePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));114JScrollPane scroller = new JScrollPane(theImage);115scroller.getVerticalScrollBar().setUnitIncrement(10);116scroller.getHorizontalScrollBar().setUnitIncrement(10);117imagePanel.add(scroller, BorderLayout.CENTER);118119// add buttons and image panels to inner panel120innerPanel.add(buttonPanel);121innerPanel.add(Box.createRigidArea(HGAP30));122innerPanel.add(imagePanel);123innerPanel.add(Box.createRigidArea(HGAP20));124}125126public JFileChooser createFileChooser() {127// create a filechooser128JFileChooser fc = new JFileChooser();129if (getSwingSet2() != null && getSwingSet2().isDragEnabled()) {130fc.setDragEnabled(true);131}132133// set the current directory to be the images directory134File swingFile = new File("resources/images/About.jpg");135if(swingFile.exists()) {136fc.setCurrentDirectory(swingFile);137fc.setSelectedFile(swingFile);138}139140return fc;141}142143144public JButton createPlainFileChooserButton() {145Action a = new AbstractAction(getString("FileChooserDemo.plainbutton")) {146public void actionPerformed(ActionEvent e) {147JFileChooser fc = createFileChooser();148149// show the filechooser150int result = fc.showOpenDialog(getDemoPanel());151152// if we selected an image, load the image153if(result == JFileChooser.APPROVE_OPTION) {154loadImage(fc.getSelectedFile().getPath());155}156}157};158return createButton(a);159}160161public JButton createPreviewFileChooserButton() {162Action a = new AbstractAction(getString("FileChooserDemo.previewbutton")) {163public void actionPerformed(ActionEvent e) {164JFileChooser fc = createFileChooser();165166// Add filefilter & fileview167javax.swing.filechooser.FileFilter filter = createFileFilter(168getString("FileChooserDemo.filterdescription"),169"jpg", "gif");170ExampleFileView fileView = new ExampleFileView();171fileView.putIcon("jpg", jpgIcon);172fileView.putIcon("gif", gifIcon);173fc.setFileView(fileView);174fc.addChoosableFileFilter(filter);175fc.setFileFilter(filter);176177// add preview accessory178fc.setAccessory(new FilePreviewer(fc));179180// show the filechooser181int result = fc.showOpenDialog(getDemoPanel());182183// if we selected an image, load the image184if(result == JFileChooser.APPROVE_OPTION) {185loadImage(fc.getSelectedFile().getPath());186}187}188};189return createButton(a);190}191192JDialog dialog;193JFileChooser fc;194195private javax.swing.filechooser.FileFilter createFileFilter(196String description, String...extensions) {197description = createFileNameFilterDescriptionFromExtensions(198description, extensions);199return new FileNameExtensionFilter(description, extensions);200}201202private String createFileNameFilterDescriptionFromExtensions(203String description, String[] extensions) {204String fullDescription = (description == null) ?205"(" : description + " (";206// build the description from the extension list207fullDescription += "." + extensions[0];208for (int i = 1; i < extensions.length; i++) {209fullDescription += ", .";210fullDescription += extensions[i];211}212fullDescription += ")";213return fullDescription;214}215216public JButton createCustomFileChooserButton() {217Action a = new AbstractAction(getString("FileChooserDemo.custombutton")) {218public void actionPerformed(ActionEvent e) {219fc = createFileChooser();220221// Add filefilter & fileview222javax.swing.filechooser.FileFilter filter = createFileFilter(223getString("FileChooserDemo.filterdescription"),224"jpg", "gif");225ExampleFileView fileView = new ExampleFileView();226fileView.putIcon("jpg", jpgIcon);227fileView.putIcon("gif", gifIcon);228fc.setFileView(fileView);229fc.addChoosableFileFilter(filter);230231// add preview accessory232fc.setAccessory(new FilePreviewer(fc));233234// remove the approve/cancel buttons235fc.setControlButtonsAreShown(false);236237// make custom controls238//wokka239JPanel custom = new JPanel();240custom.setLayout(new BoxLayout(custom, BoxLayout.Y_AXIS));241custom.add(Box.createRigidArea(VGAP10));242JLabel description = new JLabel(getString("FileChooserDemo.description"));243description.setAlignmentX(JLabel.CENTER_ALIGNMENT);244custom.add(description);245custom.add(Box.createRigidArea(VGAP10));246custom.add(fc);247248Action okAction = createOKAction();249fc.addActionListener(okAction);250251JPanel buttons = new JPanel();252buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));253buttons.add(Box.createRigidArea(HGAP10));254buttons.add(createImageButton(createFindAction()));255buttons.add(Box.createRigidArea(HGAP10));256buttons.add(createButton(createAboutAction()));257buttons.add(Box.createRigidArea(HGAP10));258buttons.add(createButton(okAction));259buttons.add(Box.createRigidArea(HGAP10));260buttons.add(createButton(createCancelAction()));261buttons.add(Box.createRigidArea(HGAP10));262buttons.add(createImageButton(createHelpAction()));263buttons.add(Box.createRigidArea(HGAP10));264265custom.add(buttons);266custom.add(Box.createRigidArea(VGAP10));267268// show the filechooser269Frame parent = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, getDemoPanel());270dialog = new JDialog(parent, getString("FileChooserDemo.dialogtitle"), true);271dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);272dialog.getContentPane().add(custom, BorderLayout.CENTER);273dialog.pack();274dialog.setLocationRelativeTo(getDemoPanel());275dialog.setVisible(true);276}277};278return createButton(a);279}280281public Action createAboutAction() {282return new AbstractAction(getString("FileChooserDemo.about")) {283public void actionPerformed(ActionEvent e) {284File file = fc.getSelectedFile();285String text;286if(file == null) {287text = getString("FileChooserDemo.nofileselected");288} else {289text = "<html>" + getString("FileChooserDemo.thefile");290text += "<br><font color=green>" + file.getName() + "</font><br>";291text += getString("FileChooserDemo.isprobably") + "</html>";292}293JOptionPane.showMessageDialog(getDemoPanel(), text);294}295};296}297298public Action createOKAction() {299return new AbstractAction(getString("FileChooserDemo.ok")) {300public void actionPerformed(ActionEvent e) {301dialog.dispose();302if (!e.getActionCommand().equals(JFileChooser.CANCEL_SELECTION)303&& fc.getSelectedFile() != null) {304305loadImage(fc.getSelectedFile().getPath());306}307}308};309}310311public Action createCancelAction() {312return new AbstractAction(getString("FileChooserDemo.cancel")) {313public void actionPerformed(ActionEvent e) {314dialog.dispose();315}316};317}318319public Action createFindAction() {320Icon icon = createImageIcon("filechooser/find.gif", getString("FileChooserDemo.find"));321return new AbstractAction("", icon) {322public void actionPerformed(ActionEvent e) {323String result = JOptionPane.showInputDialog(getDemoPanel(), getString("FileChooserDemo.findquestion"));324if (result != null) {325JOptionPane.showMessageDialog(getDemoPanel(), getString("FileChooserDemo.findresponse"));326}327}328};329}330331public Action createHelpAction() {332Icon icon = createImageIcon("filechooser/help.gif", getString("FileChooserDemo.help"));333return new AbstractAction("", icon) {334public void actionPerformed(ActionEvent e) {335JOptionPane.showMessageDialog(getDemoPanel(), getString("FileChooserDemo.helptext"));336}337};338}339340class MyImageIcon extends ImageIcon {341public MyImageIcon(String filename) {342super(filename);343};344public synchronized void paintIcon(Component c, Graphics g, int x, int y) {345g.setColor(Color.white);346g.fillRect(0,0, c.getWidth(), c.getHeight());347if(getImageObserver() == null) {348g.drawImage(349getImage(),350c.getWidth()/2 - getIconWidth()/2,351c.getHeight()/2 - getIconHeight()/2,352c353);354} else {355g.drawImage(356getImage(),357c.getWidth()/2 - getIconWidth()/2,358c.getHeight()/2 - getIconHeight()/2,359getImageObserver()360);361}362}363}364365public void loadImage(String filename) {366theImage.setIcon(new MyImageIcon(filename));367}368369public JButton createButton(Action a) {370JButton b = new JButton(a) {371public Dimension getMaximumSize() {372int width = Short.MAX_VALUE;373int height = super.getMaximumSize().height;374return new Dimension(width, height);375}376};377return b;378}379380public JButton createImageButton(Action a) {381JButton b = new JButton(a);382b.setMargin(new Insets(0,0,0,0));383return b;384}385}386387class FilePreviewer extends JComponent implements PropertyChangeListener {388ImageIcon thumbnail = null;389390public FilePreviewer(JFileChooser fc) {391setPreferredSize(new Dimension(100, 50));392fc.addPropertyChangeListener(this);393setBorder(new BevelBorder(BevelBorder.LOWERED));394}395396public void loadImage(File f) {397if (f == null) {398thumbnail = null;399} else {400ImageIcon tmpIcon = new ImageIcon(f.getPath());401if(tmpIcon.getIconWidth() > 90) {402thumbnail = new ImageIcon(403tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));404} else {405thumbnail = tmpIcon;406}407}408}409410public void propertyChange(PropertyChangeEvent e) {411String prop = e.getPropertyName();412if(prop == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {413if(isShowing()) {414loadImage((File) e.getNewValue());415repaint();416}417}418}419420public void paint(Graphics g) {421super.paint(g);422if(thumbnail != null) {423int x = getWidth()/2 - thumbnail.getIconWidth()/2;424int y = getHeight()/2 - thumbnail.getIconHeight()/2;425if(y < 0) {426y = 0;427}428429if(x < 5) {430x = 5;431}432thumbnail.paintIcon(this, g, x, y);433}434}435}436437438