Another way to customize Swing drag-and-drop is to subclass a Swing component,
define new property accessor methods for it, and then register a
TransferHandler to transfer the
value of the new property. This is what we do in Example 14-2: we define a custom
Swing component that displays the current time and uses a
TransferHandler to make the contents of its
time property available. Like
Example 14-1, this program
detect drags. It also defines a key binding so that Ctrl-C copies the time to the clipboard. This
example defines a custom component, but not a
main( ) method: use the
ShowBean program of Chapter 11 to display the component.
You may want to run
to display a
JTextField or similar
component, so that you have somewhere to drop or paste the time values
you’ve dragged or copied. Also try dropping or pasting the value into
other non-Java applications (such as your text editor) that you have
running on your desktop.
Example 14-2 also
java.text.DateFormat classes, and shows how to use the (new in Java 1.4)
ActionMap Swing classes for associating key
bindings with components.
Example 14-2. DigitalClock.java
package je3.datatransfer; import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.*; import javax.swing.Timer; // disambiguate from java.util.Timer import java.text.DateFormat; ...