下面列出了怎么用java.awt.datatransfer.DataFlavor的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Transferable clipboardCopy() throws IOException {
Transferable deflt = super.clipboardCopy();
ExTransferable enriched = ExTransferable.create(deflt);
ExTransferable.Single ex = new ExTransferable.Single(DataFlavor.stringFlavor) {
@Override
protected Object getData() {
return "<dependency>\n" + //NOI18N
" <groupId>" + record.getGroupId() + "</groupId>\n" + //NOI18N
" <artifactId>" + record.getArtifactId() + "</artifactId>\n" + //NOI18N
" <version>" + record.getVersion() + "</version>\n" + //NOI18N
"</dependency>"; //NOI18N
}
};
enriched.put(ex);
return enriched;
}
public void verifyListDataFlavorEntries() {
// Enumerate through all natives
for (Enumeration e = hashNatives.keys() ; e.hasMoreElements() ;) {
String key = (String)e.nextElement();
// SystemFlavorMap preferred value
DataFlavor value = (DataFlavor)hashNatives.get(key);
java.util.List listFlavors = flavorMap.getFlavorsForNative(key);
Vector vectorFlavors = new Vector(listFlavors);
// First element should be preferred value
DataFlavor prefFlavor = (DataFlavor)vectorFlavors.firstElement();
if ( value != prefFlavor ) {
throw new RuntimeException("\n*** Error in verifyListDataFlavorEntries()" +
"\nAPI Test: List getFlavorsForNative(String nat)" +
"\native: " + key +
"\nSystemFlavorMap preferred native: " + value.getMimeType() +
"\nList first entry: " + prefFlavor.getMimeType() +
"\nTest failed because List first entry does not match preferred");
}
}
System.out.println("*** native size = " + hashNatives.size());
}
/**
* Verifies that Lists returned from getNativesForFlavor() and
* getFlavorsForNative() are not modified with a subsequent call
* to addUnencodedNativeForFlavor() and addFlavorForUnencodedNative()
* respectively.
*/
public static void test1() {
DataFlavor df = new DataFlavor("text/plain-test1", null);
String nat = "native1";
List<String> natives = fm.getNativesForFlavor(df);
fm.addUnencodedNativeForFlavor(df, nat);
List<String> nativesNew = fm.getNativesForFlavor(df);
if (natives.equals(nativesNew)) {
System.err.println("orig=" + natives);
System.err.println("new=" + nativesNew);
throw new RuntimeException("Test failed");
}
List<DataFlavor> flavors = fm.getFlavorsForNative(nat);
fm.addFlavorForUnencodedNative(nat, df);
List<DataFlavor> flavorsNew = fm.getFlavorsForNative(nat);
if (flavors.equals(flavorsNew)) {
System.err.println("orig=" + flavors);
System.err.println("new=" + flavorsNew);
throw new RuntimeException("Test failed");
}
}
public DataFlavor[] getTransferDataFlavors()
{
if( customFlavor != null )
return new DataFlavor[]
{
customFlavor,
DATA_FLAVOR,
DataFlavor.imageFlavor
};
else
return new DataFlavor[]
{
DATA_FLAVOR,
DataFlavor.imageFlavor
};
}
public static void main(String[] args) throws InterruptedException {
Point dragSourcePoint = new Point(InterprocessArguments.DRAG_SOURCE_POINT_X_ARGUMENT.extractInt(args),
InterprocessArguments.DRAG_SOURCE_POINT_Y_ARGUMENT.extractInt(args));
Point targetFrameLocation = new Point(InterprocessArguments.TARGET_FRAME_X_POSITION_ARGUMENT.extractInt(args),
InterprocessArguments.TARGET_FRAME_Y_POSITION_ARGUMENT.extractInt(args));
String[] names = InterprocessArguments.DATA_FLAVOR_NAMES.extractStringArray(args);
DataFlavor df = DataFlavorSearcher.getByteDataFlavorForNative(names);
try {
new MissedHtmlAndRtfBug(targetFrameLocation, dragSourcePoint, df);
} catch (InterruptedException e) {
e.printStackTrace();
}
sleep(5000);
System.exit(InterprocessMessages.NO_DROP_HAPPENED);
}
/**
* Determines if the clipboard can be pasted.
*
* @return true if the clipboard contains a LibraryTreeNode XMLControl string
*/
protected boolean isClipboardPastable() {
pasteControl = null;
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable data = clipboard.getContents(null);
String dataString = null;
try {
dataString = (String)data.getTransferData(DataFlavor.stringFlavor);
} catch (Exception e) {}
if(dataString!=null) {
XMLControlElement control = new XMLControlElement();
control.readXML(dataString);
if (LibraryResource.class.isAssignableFrom(control.getObjectClass())) {
pasteControl = control;
return true;
}
}
return false;
}
@Override public boolean importData(TransferSupport support) {
try {
JFileChooser fc = (JFileChooser) support.getComponent();
List<?> list = (List<?>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
File[] files = new File[list.size()];
for (int i = 0; i < list.size(); i++) {
files[i] = (File) list.get(i);
}
if (fc.isMultiSelectionEnabled()) {
fc.setSelectedFiles(files);
} else {
File f = files[0];
if (f.isDirectory()) {
fc.setCurrentDirectory(f);
} else {
fc.setSelectedFile(f);
}
}
return true;
} catch (IOException | UnsupportedFlavorException ex) {
// ex.printStackTrace();
return false;
}
}
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
if (flavor.equals(DataFlavor.allHtmlFlavor)) {
return ALL_HTML_AS_STRING;
} else if (flavor.equals(DataFlavor.fragmentHtmlFlavor)) {
return FRAGMENT_HTML_AS_STRING;
} else if (flavor.equals(DataFlavor.selectionHtmlFlavor)) {
return SELECTION_HTML_AS_STRING;
}
}
throw new UnsupportedFlavorException(flavor);
}
protected String getCharsetForTextFormat(Long lFormat) {
long format = lFormat.longValue();
if (isMimeFormat(format, "text")) {
String nat = getNativeForFormat(format);
DataFlavor df = new DataFlavor(nat, null);
// Ignore the charset parameter of the MIME type if the subtype
// doesn't support charset.
if (!DataTransferer.doesSubtypeSupportCharset(df)) {
return null;
}
String charset = df.getParameter("charset");
if (charset != null) {
return charset;
}
}
return super.getCharsetForTextFormat(lFormat);
}
@Override public void drop(DropTargetDropEvent e) {
Component c = e.getDropTargetContext().getComponent();
getGhostGlassPane(c).ifPresent(glassPane -> {
DnDTabbedPane tabbedPane = glassPane.tabbedPane;
Transferable t = e.getTransferable();
DataFlavor[] f = t.getTransferDataFlavors();
int prev = tabbedPane.dragTabIndex;
int next = tabbedPane.getTargetTabIndex(e.getLocation());
if (t.isDataFlavorSupported(f[0]) && prev != next) {
tabbedPane.convertTab(prev, next);
e.dropComplete(true);
} else {
e.dropComplete(false);
}
glassPane.setVisible(false);
// tabbedPane.dragTabIndex = -1;
});
}
public MissedHtmlAndRtfBug(Point targetFrameLocation, Point dragSourcePoint, DataFlavor df)
throws InterruptedException {
final Frame targetFrame = new Frame("Target frame");
final TargetPanel targetPanel = new TargetPanel(targetFrame, df);
targetFrame.add(targetPanel);
targetFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
targetFrame.dispose();
}
});
targetFrame.setLocation(targetFrameLocation);
targetFrame.pack();
targetFrame.setVisible(true);
doTest(dragSourcePoint, targetPanel);
}
/**
* @see java.awt.Clipboard#getAvailableDataFlavors
* @since 1.5
*/
public DataFlavor[] getAvailableDataFlavors() {
Transferable cntnts = getContextContents();
if (cntnts != null) {
return cntnts.getTransferDataFlavors();
}
long[] formats = getClipboardFormatsOpenClose();
return DataTransferer.getInstance().
getFlavorsForFormatsAsArray(formats, getDefaultFlavorTable());
}
public static EHTMLReadMode getEHTMLReadMode (DataFlavor df) {
EHTMLReadMode mode = HTML_READ_SELECTION;
String parameter = df.getParameter("document");
if ("all".equals(parameter)) {
mode = HTML_READ_ALL;
} else if ("fragment".equals(parameter)) {
mode = HTML_READ_FRAGMENT;
}
return mode;
}
/**
* Returns a Map whose keys are all of the possible formats into which the
* Transferable's transfer data flavors can be translated. The value of
* each key is the DataFlavor in which the Transferable's data should be
* requested when converting to the format.
* <p>
* The map keys are sorted according to the native formats preference
* order.
*/
public SortedMap<Long,DataFlavor> getFormatsForTransferable(
Transferable contents, FlavorTable map)
{
DataFlavor[] flavors = contents.getTransferDataFlavors();
if (flavors == null) {
return new TreeMap();
}
return getFormatsForFlavors(flavors, map);
}
public ClipboardTransferable(SunClipboard clipboard) {
clipboard.openClipboard(null);
try {
long[] formats = clipboard.getClipboardFormats();
if (formats != null && formats.length > 0) {
// Since the SystemFlavorMap will specify many DataFlavors
// which map to the same format, we should cache data as we
// read it.
HashMap cached_data = new HashMap(formats.length, 1.0f);
Map flavorsForFormats = DataTransferer.getInstance().
getFlavorsForFormats(formats, SunClipboard.getDefaultFlavorTable());
for (Iterator iter = flavorsForFormats.keySet().iterator();
iter.hasNext(); )
{
DataFlavor flavor = (DataFlavor)iter.next();
Long lFormat = (Long)flavorsForFormats.get(flavor);
fetchOneFlavor(clipboard, flavor, lFormat, cached_data);
}
flavors = DataTransferer.getInstance().
setToSortedDataFlavorArray(flavorsToData.keySet());
}
} finally {
clipboard.closeClipboard();
}
}
/**
* Return the DataFlavors for this <code>DataContentHandler</code>.
* @return the DataFlavors
*/
public synchronized DataFlavor[] getTransferDataFlavors() {
if (transferFlavors == null) {
if (dch != null) {
transferFlavors = dch.getTransferDataFlavors();
} else {
transferFlavors = new DataFlavor[1];
transferFlavors[0] = new ActivationDataFlavor(obj.getClass(),
mimeType, mimeType);
}
}
return transferFlavors;
}
/** Get transfer data.
* @param flavor the flavor ({@link #multiFlavor})
* @return {@link MultiTransferObject} that represents data in this object
* @exception UnsupportedFlavorException when the flavor is not supported
* @exception IOException when it is not possible to read data
*/
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return transferObject;
}
@Override
public void drop(DropTargetDropEvent dtde) {
if (!dtde.isDataFlavorSupported(DataFlavor.allHtmlFlavor)) {
Sysout.println("DataFlavor.allHtmlFlavor is not present in the system clipboard");
dtde.rejectDrop();
return;
} else if (!dtde.isDataFlavorSupported(DataFlavor.fragmentHtmlFlavor)) {
Sysout.println("DataFlavor.fragmentHtmlFlavor is not present in the system clipboard");
dtde.rejectDrop();
return;
} else if (!dtde.isDataFlavorSupported(DataFlavor.selectionHtmlFlavor)) {
Sysout.println("DataFlavor.selectionHtmlFlavor is not present in the system clipboard");
dtde.rejectDrop();
return;
}
dtde.acceptDrop(DnDConstants.ACTION_COPY);
Transferable t = dtde.getTransferable();
try {
Sysout.println("ALL:");
Sysout.println(t.getTransferData(DataFlavor.allHtmlFlavor).toString());
Sysout.println("FRAGMENT:");
Sysout.println(t.getTransferData(DataFlavor.fragmentHtmlFlavor).toString());
Sysout.println("SELECTION:");
Sysout.println(t.getTransferData(DataFlavor.selectionHtmlFlavor).toString());
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
/**
* @return if the flavor is supported
*/
public boolean isDataFlavorSupported(DataFlavor df) {
Transferable localTransferable = local;
if (localTransferable != null) {
return localTransferable.isDataFlavorSupported(df);
} else {
return DataTransferer.getInstance().getFlavorsForFormats
(currentT, DataTransferer.adaptFlavorMap
(currentDT.getFlavorMap())).
containsKey(df);
}
}
private void pasteFromClipboard() {
String data = "";
try {
data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor);
List<Village> villages = PluginManager.getSingleton().executeVillageParser(data);
if (!villages.isEmpty()) {
addVillages(villages.toArray(new Village[villages.size()]));
}
} catch (HeadlessException | IOException | UnsupportedFlavorException ignored) {
}
}
/**
* Returns whether this flavor is a text type which supports the 'charset'
* parameter.
*/
public static boolean isFlavorCharsetTextType(DataFlavor flavor) {
// Although stringFlavor doesn't actually support the charset
// parameter (because its primary MIME type is not "text"), it should
// be treated as though it does. stringFlavor is semantically
// equivalent to "text/plain" data.
if (DataFlavor.stringFlavor.equals(flavor)) {
return true;
}
if (!"text".equals(flavor.getPrimaryType()) ||
!doesSubtypeSupportCharset(flavor))
{
return false;
}
Class<?> rep_class = flavor.getRepresentationClass();
if (flavor.isRepresentationClassReader() ||
String.class.equals(rep_class) ||
flavor.isRepresentationClassCharBuffer() ||
char[].class.equals(rep_class))
{
return true;
}
if (!(flavor.isRepresentationClassInputStream() ||
flavor.isRepresentationClassByteBuffer() ||
byte[].class.equals(rep_class))) {
return false;
}
String charset = flavor.getParameter("charset");
// null equals default encoding which is always supported
return (charset == null) || isEncodingSupported(charset);
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
for (DataFlavor tmp : flavors) {
if (tmp.equals(flavor)) {
return true;
}
}
return false;
}
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor)) {
return this;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
public byte[] translateTransferable(Transferable contents,
DataFlavor flavor,
long format) throws IOException
{
byte[] bytes = null;
if (format == CF_HTML) {
if (contents.isDataFlavorSupported(DataFlavor.selectionHtmlFlavor)) {
// if a user provides data represented by
// DataFlavor.selectionHtmlFlavor format, we use this
// type to store the data in the native clipboard
bytes = super.translateTransferable(contents,
DataFlavor.selectionHtmlFlavor,
format);
} else if (contents.isDataFlavorSupported(DataFlavor.allHtmlFlavor)) {
// if we cannot get data represented by the
// DataFlavor.selectionHtmlFlavor format
// but the DataFlavor.allHtmlFlavor format is avialable
// we belive that the user knows how to represent
// the data and how to mark up selection in a
// system specific manner. Therefor, we use this data
bytes = super.translateTransferable(contents,
DataFlavor.allHtmlFlavor,
format);
} else {
// handle other html flavor types, including custom and
// fragment ones
bytes = HTMLCodec.convertToHTMLFormat(super.translateTransferable(contents, flavor, format));
}
} else {
// we handle non-html types basing on their
// flavors
bytes = super.translateTransferable(contents, flavor, format);
}
return bytes;
}
public static EHTMLReadMode getEHTMLReadMode (DataFlavor df) {
EHTMLReadMode mode = HTML_READ_SELECTION;
String parameter = df.getParameter("document");
if ("all".equals(parameter)) {
mode = HTML_READ_ALL;
} else if ("fragment".equals(parameter)) {
mode = HTML_READ_FRAGMENT;
}
return mode;
}
/**
* @see java.awt.Clipboard#getAvailableDataFlavors
* @since 1.5
*/
public DataFlavor[] getAvailableDataFlavors() {
Transferable cntnts = getContextContents();
if (cntnts != null) {
return cntnts.getTransferDataFlavors();
}
long[] formats = getClipboardFormatsOpenClose();
return DataTransferer.getInstance().
getFlavorsForFormatsAsArray(formats, getDefaultFlavorTable());
}
/**
* Returns the data encapsulated in this {@link TransferableObject}.
* If the {@link Fetcher} constructor was used, then this is when
* the {@link Fetcher#getObject getObject()} method will be called.
* If the requested data flavor is not supported, then the
* {@link Fetcher#getObject getObject()} method will not be called.
*
* @param flavor The data flavor for the data to return
* @return The dropped data
* @since 1.1
*/
public Object getTransferData( java.awt.datatransfer.DataFlavor flavor )
throws java.awt.datatransfer.UnsupportedFlavorException, java.io.IOException
{
// Native object
if( flavor.equals( DATA_FLAVOR ) )
return fetcher == null ? data : fetcher.getObject();
// String
if( flavor.equals( java.awt.datatransfer.DataFlavor.stringFlavor ) )
return fetcher == null ? data.toString() : fetcher.getObject().toString();
// We can't do anything else
throw new java.awt.datatransfer.UnsupportedFlavorException(flavor);
}
/**
* Returns an object which represents the data to be transferred.
* The class of the object returned is defined by the representation class
* of the flavor.
*
* @param df The DataFlavor representing the requested type.
* @param ds The DataSource representing the data to be converted.
* @return The constructed Object.
*/
public Object getTransferData(DataFlavor df, DataSource ds)
throws IOException {
for (int i=0; i < flavor.length; i++) {
if (flavor[i].equals(df)) {
return getContent(ds);
}
}
return null;
}
private java.util.List<File> extractListOfFiles(DropTargetDropEvent dtde) {
java.util.List<File> fileList = null;
try {
fileList = (java.util.List<File>)dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return fileList;
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
DataFlavor[] flavors = getTransferDataFlavors();
for (int i = 0; i < flavors.length; i++) {
if (flavors[i].equals(flavor)) {
return true;
}
}
return false;
}