Transferable Color
/*
* This example is from the book "Java Foundation Classes in a Nutshell".
* Written by David Flanagan. Copyright (c) 1999 by O'Reilly & Associates.
* You may distribute this source code for non-commercial purposes only.
* You may study, modify, and use this example for any purpose, as long as
* this notice is retained. Note that this example is provided "as is",
* WITHOUT WARRANTY of any kind either expressed or implied.
*/
import java.awt.Color;
import java.awt.datatransfer.*;
import java.io.*;
/**
* This class is used to transfer a Color object via cut-and-paste or
* drag-and-drop. It allows a color to be transfered as a Color object,
* or as a string. Due to a long-standing bug in Java 1.1 and Java 2,
* transferring a color as a string to native Windows applications will
* not work.
*/
public class TransferableColor implements Transferable {
// This DataFlavor object is used when we transfer Color objects directly
protected static DataFlavor colorFlavor =
new DataFlavor(Color.class, "Java Color Object");
// These are the data flavors we support.
protected static DataFlavor[] supportedFlavors = {
colorFlavor, // Transfer as a Color object
DataFlavor.stringFlavor, // Transfer as a String object
DataFlavor.plainTextFlavor, // Transfer as a stream of unicode text
};
Color color; // The color we encapsulate and transfer
/** Create a new TransferableColor that encapsulates the specified color */
public TransferableColor(Color color) { this.color = color; }
/** Return a list of DataFlavors we can support */
public DataFlavor[] getTransferDataFlavors() { return supportedFlavors; }
/** Check whether a specified DataFlavor is available */
public boolean isDataFlavorSupported(DataFlavor flavor) {
if (flavor.equals(colorFlavor) ||
flavor.equals(DataFlavor.stringFlavor) ||
flavor.equals(DataFlavor.plainTextFlavor)) return true;
return false;
}
/**
* Transfer the data. Given a specified DataFlavor, return an Object
* appropriate for that flavor. Throw UnsupportedFlavorException if we
* don't support the requested flavor.
*/
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException
{
if (flavor.equals(colorFlavor)) return color;
else if (flavor.equals(DataFlavor.stringFlavor)) return color.toString();
else if (flavor.equals(DataFlavor.plainTextFlavor))
return new ByteArrayInputStream(color.toString().getBytes("Unicode"));
else throw new UnsupportedFlavorException(flavor);
}
}
Related examples in the same category