001    package de.mospace.swing;
002    
003    /* Mp3dings - manage mp3 meta-information
004    * Copyright (C) 2006 Moritz Ringler
005    * $Id: PathInput.java 69 2007-10-24 21:57:43Z ringler $
006    *
007    * This program is free software; you can redistribute it and/or
008    * modify it under the terms of the GNU General Public License
009    * as published by the Free Software Foundation; either version 2
010    * of the License, or (at your option) any later version.
011    *
012    * This program is distributed in the hope that it will be useful,
013    * but WITHOUT ANY WARRANTY; without even the implied warranty of
014    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015    * GNU General Public License for more details.
016    *
017    * You should have received a copy of the GNU General Public License
018    * along with this program; if not, write to the Free Software
019    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
020    */
021    
022    import java.awt.datatransfer.DataFlavor;
023    import java.awt.datatransfer.StringSelection;
024    import java.awt.datatransfer.Transferable;
025    import java.awt.datatransfer.UnsupportedFlavorException;
026    import java.awt.event.ActionEvent;
027    import java.awt.event.ActionListener;
028    import java.io.File;
029    import java.io.IOException;
030    import java.util.Arrays;
031    import java.util.List;
032    import javax.swing.AbstractAction;
033    import javax.swing.Box;
034    import javax.swing.BoxLayout;
035    import javax.swing.JButton;
036    import javax.swing.JComponent;
037    import javax.swing.JFileChooser;
038    import javax.swing.JTextField;
039    import javax.swing.SwingUtilities;
040    import javax.swing.TransferHandler;
041    import javax.swing.filechooser.FileFilter;
042    import javax.swing.event.EventListenerList;
043    import java.util.logging.Logger;
044    
045    /**
046    * @author Moritz Ringler
047    * @version $Revision: 69 $ ($Date: 2007-10-24 23:57:43 +0200 (Mi, 24 Okt 2007) $)
048    */
049    public class PathInput extends Box{
050        private static final Logger logger = Logger.getLogger(PathInput.class.getPackage().getName());
051        protected JTextField textfield = new JTextField(40);
052        private JButton button;
053        int selectionMode = JFileChooser.FILES_ONLY;
054        private String extension;
055    
056        /*
057         *  Event generation and listener management
058         */
059        private EventListenerList listenerList = new EventListenerList();
060        private transient ActionEvent event = null;
061        private String actionCommand = null;
062    
063        public PathInput(String path, String extension){
064            this(path);
065            this.extension = extension;
066        }
067    
068        public PathInput(String path){
069            super(BoxLayout.X_AXIS);
070            textfield.setText(path);
071            textfield.setTransferHandler(new FileTransferHandler(textfield.getTransferHandler()));
072            textfield.addActionListener(new ActionListener(){
073                    public void actionPerformed(ActionEvent e){
074                        event = e;
075                        PathInput.this.fireActionPerformed();
076                    }
077            });
078            add(textfield);
079            add(Box.createHorizontalStrut(2));
080            button = new JButton(new AbstractAction(GLOBALS.getString("...")){
081                public void actionPerformed(ActionEvent e){
082                    browse();
083                }
084            });
085            add(button);
086            setMaximumSize(getPreferredSize());
087        }
088    
089        public PathInput(String path, int fileSelectionMode){
090            this(path);
091            selectionMode = fileSelectionMode;
092        }
093    
094        protected void browse(){
095            String path = getPath();
096            if(path.length() == 0){
097                path = ".";
098            }
099            JFileChooser jfc = new JFileChooser(path);
100            jfc.setFileSelectionMode(selectionMode);
101            if(extension != null){
102                jfc.setFileFilter(new ExtensionFileFilter(null,
103                    extension.replaceAll("\\*", "").split("\\s+")));
104            }
105            try{
106                File pwd = new File(getPath());
107                if(!pwd.isDirectory()){
108                    pwd = pwd.getAbsoluteFile().getParentFile();
109                }
110                if(pwd.isDirectory()){
111                    jfc.setCurrentDirectory(pwd);
112                }
113            } catch (Exception ex){
114                ex.printStackTrace();
115            }
116            if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION
117                    && jfc.getSelectedFile() != null){
118                textfield.setText(jfc.getSelectedFile().getAbsolutePath());
119                fireActionPerformed();
120            }
121        }
122    
123        public void setPath(String p){
124            textfield.setText(p);
125            fireActionPerformed();
126        }
127    
128        public String getPath(){
129            return textfield.getText();
130        }
131    
132        public JTextField getTextfield(){
133            return textfield;
134        }
135    
136        public void setEnabled(boolean on){
137            super.setEnabled(on);
138            textfield.setEnabled(on);
139            button.setEnabled(on);
140        }
141    
142        public void addActionListener(ActionListener a){
143            listenerList.add(ActionListener.class, a);
144        }
145    
146        public void removeActionListener(ActionListener a){
147            listenerList.remove(ActionListener.class, a);
148        }
149    
150        private String getActionCommand(){
151            return (actionCommand == null)? textfield.getText() : actionCommand;
152        }
153    
154        public void setActionCommand(String s){
155            actionCommand = s;
156            textfield.setActionCommand(s);
157        }
158    
159        /**  Informs listeners that something has changed. */
160        protected void fireActionPerformed() {
161            Object[] listeners = listenerList.getListenerList();
162    
163            /*
164            *  Process the listeners last to first, notifying
165            *  those that are interested in this event
166            */
167            for (int i = listeners.length - 2; i >= 0; i -= 2) {
168                if (listeners[i] == ActionListener.class) {
169                    if(event == null){
170                        event = new ActionEvent(this,
171                            ActionEvent.ACTION_PERFORMED,
172                            getActionCommand());
173                    }
174                    ((ActionListener) listeners[i + 1]).actionPerformed(event);
175                }
176            }
177            event = null;
178        }
179    
180        private class FileTransferHandler extends TransferHandler{
181            private final TransferHandler parent;
182    
183            public FileTransferHandler(TransferHandler parent){
184                this.parent =  parent;
185            }
186    
187            public boolean canImport(JComponent comp, DataFlavor[] flavor){
188                boolean result =
189                    Arrays.asList(flavor).contains(DataFlavor.javaFileListFlavor);
190                if(! result){
191                    result = (parent == null)
192                        ? super.canImport(comp, flavor)
193                        : parent.canImport(comp, flavor);
194                }
195                return result;
196            }
197    
198            public int getSourceActions(JComponent comp){
199                return COPY_OR_MOVE;
200            }
201    
202            public Transferable createTransferable(JComponent c){
203                return new StringSelection(textfield.getSelectedText());
204            }
205    
206            public boolean importData(JComponent comp, Transferable t){
207                boolean result = false;
208                if(
209                     t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)
210                ){
211                    List data = null;
212                    try{
213                       data = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
214                    } catch (UnsupportedFlavorException ex){
215                        throw new Error(ex);
216                    } catch (IOException ex){
217                        logger.severe(ex.toString());
218                    }
219                    if(data != null && !data.isEmpty()){
220                        textfield.setText(((File) data.get(0)).getAbsolutePath());
221                        result = true;
222                    }
223                } else {
224                    if(parent == null) {
225                        result = super.importData(comp, t);
226                    } else {
227                        result = parent.importData(comp, t);
228                    }
229                }
230                if(result){
231                    SwingUtilities.invokeLater(new Runnable(){
232                        public void run(){
233                            fireActionPerformed();
234                        }
235                    });
236                }
237                return result;
238            }
239    
240        }
241    }