1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.gui.dnd;
21
22 import java.awt.datatransfer.Transferable;
23 import java.io.File;
24 import java.util.Collections;
25 import java.util.List;
26 import javax.swing.JComponent;
27 import javax.swing.JTextField;
28 import javax.swing.TransferHandler;
29
30
31 /***
32 * Provides a default file transfer handler for {@link JTextField}s.
33 * <p>
34 * When creating a transferable the text of the textfield is interpreted as the
35 * absolute path of the file.
36 * <p>
37 * When a file is dropped on the text field, the file's absolute path replaces
38 * the current text of the text field.
39 * <p>
40 * Use the static {@link #install(JTextField)} method to install it for a text
41 * field.
42 * @author Felix Berger
43 */
44 public class DefaultTextFieldFileTransferHandler extends AbstractFileTransferHandler
45 {
46
47 private static TransferHandler handler = new DefaultTextFieldFileTransferHandler();
48
49 protected DefaultTextFieldFileTransferHandler()
50 {
51 }
52
53 /***
54 * Installs the default file transfer handler for this <code>textField</code>
55 * <p>
56 * Does not activate dragging, call
57 * {@link javax.swing.text.JTextComponent#setDragEnabled(boolean)}
58 * to enable it.
59 * <p>
60 * The transfer handler can be be removed by calling
61 * {@link JComponent#setTransferHandler(javax.swing.TransferHandler)
62 * textField.setTransferHandler(null)}.
63 * @param textField
64 */
65 public static void install(JTextField textField)
66 {
67 textField.setTransferHandler(handler);
68 }
69
70 /***
71 * Returns null, if the text field is empty or disabled.
72 */
73 @Override
74 protected Transferable createTransferable(JComponent c)
75 {
76 JTextField textField = (JTextField)c;
77 if (textField.isEnabled() && textField.getText().length() > 0) {
78 return new FileTransferable(Collections.singletonList(new File(textField.getText())));
79 }
80 return null;
81 }
82
83 /***
84 * Overriden to set the text of the textfield to the absolute path of the
85 * first file of the list.
86 */
87 @Override
88 public boolean importFiles(JComponent comp, List<File> files)
89 {
90 File file = files.get(0);
91 JTextField textField = (JTextField)comp;
92 textField.setText(file.getAbsolutePath());
93 return true;
94 }
95
96 }