Java Reference
In-Depth Information
Example 13−1: SimpleCutAndPaste.java (continued)
* This method implements the ClipboardOwner interface. It is called when
* something else is placed on the clipboard.
**/
public void lostOwnership(Clipboard c, Transferable t) {
// Un-highlight the text field, since we don't "own" the clipboard
// anymore, and the text is no longer available to be pasted.
field.select(0,0);
}
}
A Transferable Data Type
The java.awt.datatransfer.StringSelection class makes it simple to transfer
String values between applications. To transfer other types of data, however, you
must create a custom implementation of the Transferable interface. Example 13-2
shows the Scribble class—a data type that represents a set of line segments. It
implements the Shape interface, so it can be drawn with the Java 2D API (see
Chapter 11, Graphics ). More important, it implements the Transferable interface,
so that scribbles can be transferred from one application to another.
The Scribble class actually supports data transfer using two data flavors. It defines
a custom flavor that transfers serialized Scribble instances. However, as noted at
the beginning of the chapter, custom flavors like these do not work for data trans-
fer between independent JVMs (at least with Sun's Java implementations). There-
fore, Scribble also allows itself to be transferred as a String and defines methods
for converting scribbles to and from string form. Note that Example 13-2 doesn't
demonstrate cut-and-paste or drag-and-drop data transfer; it simply defines the
data-transfer infrastructure used by the cut-and-paste and drag-and-drop examples
that follow. It's also worth studying as a custom Shape implementation.
Example 13−2: Scribble.java
package com.davidflanagan.examples.datatransfer;
import java.awt.*;
import java.awt.geom.*;
import java.awt.datatransfer.*;
import java.io.Serializable;
import java.util.StringTokenizer;
/**
* This class represents a scribble composed of any number of "polylines".
* Each "polyline" is set of connected line segments. A scribble is created
* through a series of calls to the moveto() and lineto() methods. moveto()
* specifies the starting point of a new polyline, and lineto() adds a new
* point to the end of the current polyline().
*
* This class implements the Shape interface which means that it can be drawn
* using the Java2D graphics API
*
* It also implements the Transferable interface, which means that it can
* easily be used with cut-and-paste and drag-and-drop. It defines a custom
* DataFlavor, scribbleDataFlavor, which transfers Scribble objects as Java
* objects. However, it also supports cut-and-paste and drag-and-drop based
* on a portable string representation of the scribble. The toString()
Search WWH ::




Custom Search