Dropping Multiple Datatypes

A limitation of the Swing data transfer mechanism is that, by default, it supports only a single type of data. It is useful, sometimes, to allow a component to accept pastes and drops of more than one type, handling each type in a different way. A JEditorPane component might handle dropped text in one way, handle dropped colors another way (by changing the foreground color of the selected text, for example), and handle dropped files yet another way (for example, by inserting the contents of the file). In the previous examples, we’ve created our own TransferHandler instances for simple data transfer customization. For more complex customizations, such as supporting multiple drop types, we need to subclass TransferHandler.

Example 14-3 lists the FileTransferHandler class. It is a TransferHandler subclass that wraps and delegates to some other specified TransferHandler, adding the ability to accept pastes and drops of files using the predefined DataFlavor.javaFileListFlavor flavor. The example includes an inner class named Test that demonstrates its use with a JTextArea and a JFileChooser. Depending on how well integrated your Java implementation is with your operating system’s desktop, you may also be able to drag files from your desktop into the JTextArea.

Example 14-3. FileTransferHandler.java

package je3.datatransfer; import javax.swing.*; import java.awt.datatransfer.*; import java.io.*; import java.awt.event.InputEvent; import java.util.List; /** * This ...

Get Java Examples in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.