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

Custom Data Transfer

Example 14-5 is a custom Swing component named TransferableScribblePane. It allows the user to scribble with the mouse and to select one scribble at a time. It defines cut( ), copy( ), and paste( ) methods that operate on the selected line, and also allows the selected line to be dragged and dropped within the component or into another instance of the component. The scribbles are transferred using the TransferablePolyLine class defined in Example 14-4, of course.

This example does not use the high-level Swing TransferHandler class, but instead relies on the underlying data transfer and drag-and-drop architecture of java.awt.datatransfer and java.awt.dnd . The code for performing drag-and-drop is substantially more complex than the code for cut-and-paste. This is because the asynchronous drag-and-drop model requires a number of distinct event listeners and their corresponding event objects. The key interfaces are DragGestureListener, which triggers a new drag, and DragSourceListener and DropTargetListener, which notify the source of a drag and the target of a drop of important events that occur during the drag-and-drop process. The example implements all three interfaces as anonymous inner classes. When studying the example, pay particular attention to the dragGestureRecognized( ) method of the DragSourceListener and the drop( ) method of the DropTargetListener. The first is where the drag is initiated, and the second is where the data transfer actually transpires. ...

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