mergedoc.ui.FileChooserField.java Source code

Java tutorial

Introduction

Here is the source code for mergedoc.ui.FileChooserField.java

Source

/*
 * Copyright (c) 2003- Shinji Kashihara. All rights reserved.
 * This program are made available under the terms of the Common Public License
 * v1.0 which accompanies this distribution, and is available at cpl-v10.html.
 */
package mergedoc.ui;

import java.awt.Dimension;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.filechooser.FileFilter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ???
 * @author Shinji Kashihara
 */
public class FileChooserField extends JPanel {

    /**  */
    private static final Log log = LogFactory.getLog(FileChooserField.class);

    /**  */
    private final JLabel label = new JLabel();

    /**  */
    private final JTextField textField = new JTextField();

    /**  */
    private final JButton button = new JButton();

    /**  */
    private final JComboBox combo = new JComboBox();

    /** ? */
    private JFileChooser chooser = new JFileChooser();

    /** ?? */
    private ActionListener chooseListener;

    /**  */
    public static final String ENCODING_DEFAULT = System.getProperty("file.encoding");

    /**  */
    public static final String ENCODING_AUTO = "JISAutoDetect";

    /** ? */
    private static interface SelectionMode {
        void apply(JFileChooser chooser);
    }

    /** ? */
    public static final SelectionMode DIRECTORIES = new SelectionMode() {
        @Override
        public void apply(JFileChooser chooser) {
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.removeChoosableFileFilter(chooser.getFileFilter());
            chooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.isDirectory();
                }

                @Override
                public String getDescription() {
                    return "??";
                }
            });
        }
    };

    /** ZIP ? */
    public static final SelectionMode ZIP_FILES = new SelectionMode() {
        @Override
        public void apply(JFileChooser chooser) {
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().endsWith(".zip") || f.getName().endsWith(".jar");
                }

                @Override
                public String getDescription() {
                    return "*.zip, *.jar";
                }
            });
        }
    };

    /** ZIP, TGZ ? */
    public static final SelectionMode ZIP_TGZ_FILES = new SelectionMode() {
        @Override
        public void apply(JFileChooser chooser) {
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().endsWith(".zip") || f.getName().endsWith(".jar")
                            || f.getName().endsWith(".tgz") || f.getName().endsWith(".tar.gz");
                }

                @Override
                public String getDescription() {
                    return "*.zip, *.jar, *.tgz, *.tar.gz";
                }
            });
        }
    };

    /**
     * ??
     */
    public FileChooserField() {

        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

        // ?
        int maxWidth = (int) ComponentFactory.createMaxDimension().getWidth();
        textField.setMaximumSize(new Dimension(maxWidth, 20));
        textField.setTransferHandler(new FileDropHandler());

        // ?
        ComponentFactory.ensureSize(button, 20, 18);
        button.setText("...");

        // ??
        CharsetSortedModel charsetModel = new CharsetSortedModel();
        charsetModel.add("EUC-JP");
        charsetModel.add("EUC-JP-LINUX");
        charsetModel.add("ISO-2022-JP");
        charsetModel.add("MS932");
        charsetModel.add("Shift_JIS");
        charsetModel.add("UTF-16");
        charsetModel.add("UTF-16BE");
        charsetModel.add("UTF-16LE");
        charsetModel.add("UTF-8");
        charsetModel.add(ENCODING_DEFAULT);
        charsetModel.fireAdded();

        // ???
        add(label);
        add(ComponentFactory.createSpacer(10, 0));
        add(textField);
        add(button);
        add(ComponentFactory.createSpacer(5, 0));
        add(combo);

        // ??
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int result = chooser.showOpenDialog(FileChooserField.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    setFile(chooser.getSelectedFile());
                    if (chooseListener != null) {
                        chooseListener.actionPerformed(e);
                    }
                }
            }
        });
    }

    /**
     * ??????
     * @param mode ?
     */
    public void setSelectionMode(SelectionMode mode) {
        chooser = new JFileChooser();
        mode.apply(chooser);
    }

    /**
     * ?????
     * @param chooseListener ??
     */
    public void setChooseListener(ActionListener chooseListener) {
        this.chooseListener = chooseListener;
    }

    /**
     * ????
     * @return 
     */
    public JLabel getLabel() {
        return label;
    }

    /**
     * ???
     * @param file 
     */
    public void setFile(File file) {
        textField.setText(file.getPath());
        chooser.setSelectedFile(file);
    }

    /**
     * ????
     * @return 
     */
    public File getFile() {
        return new File(textField.getText());
    }

    /**
     * ????
     * @return 
     */
    public JComboBox getComboBox() {
        return combo;
    }

    /**
     * ????????<p>
     * 
     * ???????????????
     * ???? String ? {@link String(byte[],String)}
     * ???{@link Charset#isSupported} ? JISAutoDetect ??
     * ??????JDK1.4.1 ?? ISO-2022-JP ?? false ???
     * ???<p>
     * 
     * ???????????????????????
     */
    private class CharsetSortedModel extends DefaultComboBoxModel {

        private final Set<Object> charsetNames;

        private CharsetSortedModel() {
            charsetNames = new TreeSet<Object>();
        }

        private CharsetSortedModel(Set<Object> set) {
            super(set.toArray());
            charsetNames = set;
        }

        private boolean isSupported(Object charset) {
            try {
                new String(new byte[0], charset.toString());
            } catch (UnsupportedEncodingException e) {
                return false;
            }
            return true;
        }

        private void add(Object charset) {
            if (isSupported(charset)) {
                charsetNames.add(charset);
            }
        }

        private void fireAdded() {
            combo.setModel(new CharsetSortedModel(charsetNames));
        }

        @Override
        public void addElement(Object charset) {
            if (isSupported(charset) && !charsetNames.contains(charset)) {
                charsetNames.add(charset);
                fireAdded();
            }
        }

        @Override
        public void setSelectedItem(Object charset) {
            if (charset != null) {
                if (!charsetNames.contains(charset)) {
                    addElement(charset);
                }
                super.setSelectedItem(charset);
            }
        }
    }

    /**
     * ????????
     * ??????????????
     * &?????????????
     */
    private class FileDropHandler extends TransferHandler {

        TransferHandler originHandler = textField.getTransferHandler();

        @Override
        public void exportToClipboard(JComponent comp, Clipboard clipboard, int action) {
            originHandler.exportToClipboard(comp, clipboard, action);
        }

        @Override
        public int getSourceActions(JComponent comp) {
            return originHandler.getSourceActions(comp);
        }

        @Override
        public boolean canImport(JComponent comp, DataFlavor[] flavors) {
            for (DataFlavor flavor : flavors) {
                if (flavor.isFlavorJavaFileListType()) {
                    return true;
                }
            }
            return originHandler.canImport(comp, flavors);
        }

        @Override
        public boolean importData(JComponent comp, Transferable t) {
            boolean imported = false;
            if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                try {
                    List files = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                    File file = (File) files.get(0);
                    setFile(file);
                    textField.repaint();
                    imported = true;
                } catch (UnsupportedFlavorException e) {
                } catch (IOException e) {
                }
            } else {
                imported = originHandler.importData(comp, t);
            }
            if (imported && chooseListener != null && getFile().exists()) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        chooseListener.actionPerformed(null);
                    }
                });
            }
            return imported;
        }
    }
}