Java Reference
In-Depth Information
public interface Transferable{
public DataFlavor[] getTransferDataFlavors();
public boolean isDataFlavorSupported(DataFlavor);
public Object getTransferData(java.awt.datatransfer.DataFlavor)
throws UnsupportedFlavorException, IOException;
}
One common application for this is the ability to transfer images. The exposed property of
a
JLabel
or
JButton
is a
javax.swing.Icon
object, not a
java.awt.Image
object. While you can
certainly transfer
Icon
objects within and across Java programs, a more useful behavior is to
transfer
Image
objects to external entities, like Paint Shop Pro or Photoshop.
To create a transferable image object, the
ImageSelection
class, you must implement
the three
Transferable
interface methods and override four methods of
TransferHandler
:
getSourceActions()
,
canImport()
,
createTransferable()
, and
importData()
.
■
Note
The class for transferring strings is called
StringSelection
.
The
getSourceActions()
method needs to report which actions you are going to support.
By default, this is the
TransferHandler.COPY
operation when a property is set via the constructor, or
TransferHandler.NONE
when it is not. Since the
ImageSelection
class implicitly uses the
icon
property to get the component's image, just have the method return
TransferHandler.COPY
:
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
There is also a
TransferHandler.MOVE
operation, but you typically don't want the image to
be removed from the label it was copied from.
You pass the
canImport()
method a component and an array of
DataFlavor
objects. You
need to verify that the component is supported and one of the flavors in the array matches the
supported set:
private static final DataFlavor flavors[] = {DataFlavor.imageFlavor};
...
public boolean canImport(JComponent comp, DataFlavor flavor[]) {
if (!(comp instanceof JLabel) && !(comp instanceof AbstractButton)) {
return false;
}
for (int i=0, n=flavor.length; i<n; i++) {
for (int j=0, m=flavors.length; j<m; j++) {
if (flavor[i].equals(flavors[j])) {
return true;
}
}
}
return false;
}