A Clock with Drag and Copy Support
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
new time
property available. Like
Example 14-1, this program
uses a MouseMotionListener
to
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 ShowBean
again
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
demonstrates the javax.swing.Timer
and java.text.DateFormat
classes, and shows how to use the (new in Java 1.4)
InputMap
and 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; ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.