O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required