Example usage for java.awt.datatransfer Transferable isDataFlavorSupported

List of usage examples for java.awt.datatransfer Transferable isDataFlavorSupported

Introduction

In this page you can find the example usage for java.awt.datatransfer Transferable isDataFlavorSupported.

Prototype

public boolean isDataFlavorSupported(DataFlavor flavor);

Source Link

Document

Returns whether or not the specified data flavor is supported for this object.

Usage

From source file:ColorSink.java

public void pastecolor() {
    // Get the clipboard, and read its contents
    Clipboard c = this.getToolkit().getSystemClipboard();
    Transferable t = c.getContents(this);
    if (t == null) { // If nothing to paste
        this.getToolkit().beep(); // then beep and do nothing
        return;/*from  ww w .  j av  a 2s.co  m*/
    }
    try {
        // If the clipboard contained a color, use it as the background color
        if (t.isDataFlavorSupported(TransferableColor.colorFlavor)) {
            Color color = (Color) t.getTransferData(TransferableColor.colorFlavor);
            this.setBackground(color);
        }
        // If the clipboard contained text, insert it.
        else if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            String s = (String) t.getTransferData(DataFlavor.stringFlavor);
            this.replaceSelection(s);
        }
        // Otherwise, we don't know how to paste the data, so just beep.
        else
            this.getToolkit().beep();
    } catch (UnsupportedFlavorException ex) {
        this.getToolkit().beep();
    } catch (IOException ex) {
        this.getToolkit().beep();
    }
}

From source file:org.apache.openmeetings.screenshare.job.RemoteJob.java

public String getClipboardText() {
    try {//from   w  ww .  ja va 2 s  . com
        // get the system clipboard
        Clipboard systemClipboard = getDefaultToolkit().getSystemClipboard();
        // get the contents on the clipboard in a transferable object
        Transferable clipboardContents = systemClipboard.getContents(null);
        // check if clipboard is empty
        if (clipboardContents == null) {
            // Clipboard is empty!!!
        } else if (clipboardContents.isDataFlavorSupported(stringFlavor)) {
            // see if DataFlavor of DataFlavor.stringFlavor is supported
            // return text content
            String returnText = (String) clipboardContents.getTransferData(stringFlavor);
            return returnText;
        }
    } catch (Exception e) {
        log.error("Unexpected exception while getting clipboard text", e);
    }
    return "";
}

From source file:TreeDragTest.java

public void drop(DropTargetDropEvent dtde) {
    Point pt = dtde.getLocation();
    DropTargetContext dtc = dtde.getDropTargetContext();
    JTree tree = (JTree) dtc.getComponent();
    TreePath parentpath = tree.getClosestPathForLocation(pt.x, pt.y);
    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) parentpath.getLastPathComponent();
    if (parent.isLeaf()) {
        dtde.rejectDrop();//ww  w  . ja va 2  s  . c o m
        return;
    }

    try {
        Transferable tr = dtde.getTransferable();
        DataFlavor[] flavors = tr.getTransferDataFlavors();
        for (int i = 0; i < flavors.length; i++) {
            if (tr.isDataFlavorSupported(flavors[i])) {
                dtde.acceptDrop(dtde.getDropAction());
                TreePath p = (TreePath) tr.getTransferData(flavors[i]);
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
                DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                model.insertNodeInto(node, parent, 0);
                dtde.dropComplete(true);
                return;
            }
        }
        dtde.rejectDrop();
    } catch (Exception e) {
        e.printStackTrace();
        dtde.rejectDrop();
    }
}

From source file:FileTransferHandler.java

/**
 * If the wrapped handler can import strings and the specified Transferable
 * can provide its data as a List of File objects, then we read the files, and
 * pass their contents as a string to the wrapped handler. Otherwise, we offer
 * the Transferable to the wrapped handler to handle on its own.
 *//*from  ww  w .j a v a2  s.c o m*/
public boolean importData(JComponent c, Transferable t) {
    // See if we're offered a java.util.List of java.io.File objects.
    // We handle this case first because the Transferable is likely to
    // also offer the filenames as strings, and we want to import the
    // file contents, not their names!
    if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)
            && wrappedHandler.canImport(c, stringFlavorArray)) {
        try {
            List filelist = (List) t.getTransferData(DataFlavor.javaFileListFlavor);

            // Loop through the files to determine total size
            int numfiles = filelist.size();
            int numbytes = 0;
            for (int i = 0; i < numfiles; i++) {
                File f = (File) filelist.get(i);
                numbytes += (int) f.length();
            }

            // There will never be more characters than bytes in the files
            char[] text = new char[numbytes]; // to hold file contents
            int p = 0; // current position in the text[] array

            // Loop through the files again, reading their content as text
            for (int i = 0; i < numfiles; i++) {
                File f = (File) filelist.get(i);
                Reader r = new BufferedReader(new FileReader(f));
                p += r.read(text, p, (int) f.length());
            }

            // Convert the character array to a string and wrap it
            // in a pre-defined Transferable class for transferring strings
            StringSelection selection = new StringSelection(new String(text, 0, p));

            // Ask the wrapped handler to import the string
            return wrappedHandler.importData(c, selection);
        }
        // If anything goes wrong, just beep to tell the user
        catch (UnsupportedFlavorException e) {
            c.getToolkit().beep(); // audible error
            return false; // return failure code
        } catch (IOException e) {
            c.getToolkit().beep(); // audible error
            return false; // return failure code
        }
    }

    // Otherwise let the wrapped class handle this transferable itself
    return wrappedHandler.importData(c, t);
}

From source file:net.sf.nmedit.patchmodifier.mutator.VariationTransferHandler.java

public boolean importData(JComponent c, Transferable t) {
    //System.out.println("import data");
    Variation target;//from   w  w  w . j  a  va 2s. c  o  m
    Vector<Integer> data = null;

    if (!canImport(c, t.getTransferDataFlavors())) {
        return false;
    }

    try {
        target = (Variation) c;

        if (t.isDataFlavorSupported(variationFlavor)) {
            data = ((VariationTransferData) t.getTransferData(variationFlavor)).getVariationData();
        } else {
            return false;
        }
    } catch (UnsupportedFlavorException ufe) {
        if (log.isErrorEnabled()) {
            log.error("importData: unsupported data flavor", ufe);
        }
        return false;
    } catch (IOException ioe) {
        if (log.isErrorEnabled()) {
            log.error("importData: I/O exception", ioe);
        }
        return false;
    }

    target.getState().updateValues(new Vector<Integer>(data));

    c.repaint();
    return true;
}

From source file:Samples.Advanced.GraphEditorDemo.java

/**
* Get the String residing on the clipboard.
*
* @return any text found on the Clipboard; if none found, return an
* empty String./*  w  ww .  j a va 2  s  .  c  o m*/
*/
public String getClipboardContents() {
    String result = "";
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    //odd: the Object param of getContents is not currently used
    Transferable contents = clipboard.getContents(null);
    boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor);
    if (hasTransferableText) {
        try {
            result = (String) contents.getTransferData(DataFlavor.stringFlavor);
        } catch (UnsupportedFlavorException ex) {
            //highly unlikely since we are using a standard DataFlavor
            System.out.println(ex);
            ex.printStackTrace();
        } catch (IOException ex) {
            System.out.println(ex);
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:net.sf.jabref.gui.fieldeditors.FileListEditorTransferHandler.java

@Override
public boolean importData(JComponent comp, Transferable t) {
    // If the drop target is the main table, we want to record which
    // row the item was dropped on, to identify the entry if needed:

    try {/*from  w  ww .jav a  2s. c  o  m*/

        List<File> files = new ArrayList<>();
        // This flavor is used for dragged file links in Windows:
        if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            files.addAll((List<File>) t.getTransferData(DataFlavor.javaFileListFlavor));
        }

        if (t.isDataFlavorSupported(urlFlavor)) {
            URL dropLink = (URL) t.getTransferData(urlFlavor);
            LOGGER.debug("URL: " + dropLink);
        }

        // This is used when one or more files are pasted from the file manager
        // under Gnome. The data consists of the file paths, one file per line:
        if (t.isDataFlavorSupported(stringFlavor)) {
            String dropStr = (String) t.getTransferData(stringFlavor);
            files.addAll(EntryTableTransferHandler.getFilesFromDraggedFilesString(dropStr));
        }

        SwingUtilities.invokeLater(() -> {
            for (File file : files) {
                // Find the file's extension, if any:
                String name = file.getAbsolutePath();
                FileUtil.getFileExtension(name).ifPresent(extension -> ExternalFileTypes.getInstance()
                        .getExternalFileTypeByExt(extension).ifPresent(fileType -> {
                            if (droppedFileHandler == null) {
                                droppedFileHandler = new DroppedFileHandler(frame, frame.getCurrentBasePanel());
                            }
                            droppedFileHandler.handleDroppedfile(name, fileType, entryContainer.getEntry());
                        }));
            }
        });
        if (!files.isEmpty()) {
            // Found some files, return
            return true;
        }
    } catch (IOException ioe) {
        LOGGER.warn("Failed to read dropped data. ", ioe);
    } catch (UnsupportedFlavorException | ClassCastException ufe) {
        LOGGER.warn("Drop type error. ", ufe);
    }

    // all supported flavors failed
    StringBuilder logMessage = new StringBuilder("Cannot transfer input:");
    DataFlavor[] inflavs = t.getTransferDataFlavors();
    for (DataFlavor inflav : inflavs) {
        logMessage.append(' ').append(inflav);
    }
    LOGGER.warn(logMessage.toString());

    return false;
}

From source file:com.mirth.connect.client.ui.TemplatePanel.java

public void dragEnter(DropTargetDragEvent dtde) {
    try {/* w  ww  .jav  a2  s.c  o m*/
        Transferable tr = dtde.getTransferable();

        if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
            List<File> fileList = (List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor);
            Iterator<File> iterator = fileList.iterator();

            while (iterator.hasNext()) {
                iterator.next();
            }
        } else {
            dtde.rejectDrag();
        }
    } catch (Exception e) {
        dtde.rejectDrag();
    }
}

From source file:com.mirth.connect.client.ui.TemplatePanel.java

public void drop(DropTargetDropEvent dtde) {
    try {/* ww w. j  a v  a 2s .  c o  m*/
        Transferable tr = dtde.getTransferable();

        if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            File file = ((List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor)).get(0);

            String dataType = PlatformUI.MIRTH_FRAME.displayNameToDataType.get(getDataType());
            DataTypeClientPlugin dataTypePlugin = LoadedExtensions.getInstance().getDataTypePlugins()
                    .get(dataType);
            if (dataTypePlugin.isBinary()) {
                byte[] content = FileUtils.readFileToByteArray(file);

                // The plugin should decide how to convert the byte array to string
                pasteBox.setText(dataTypePlugin.getTemplateString(content));
            } else {
                pasteBox.setText(FileUtils.readFileToString(file, UIConstants.CHARSET));
            }

            parent.modified = true;
        }
    } catch (Exception e) {
        dtde.rejectDrop();
    }
}

From source file:net.rptools.tokentool.ui.TokenCompositionPanel.java

public void drop(DropTargetDropEvent dtde) {

    Transferable transferable = dtde.getTransferable();
    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

    try {//from w ww.j  a  v a 2  s  .co m
        if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            List<URL> urls = new FileTransferableHandler().getTransferObject(transferable);

            for (URL url : urls) {
                String baseName = java.net.URLDecoder.decode(FilenameUtils.getBaseName(url.getFile()), "UTF-8");
                TokenTool.getFrame().getControlPanel().setNamePrefixField(baseName);
            }
        }
    } catch (UnsupportedFlavorException | IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        Image image = new ImageTransferableHandler().getTransferObject(transferable);
        if (!(image instanceof BufferedImage)) {
            // Convert to buffered image
            image = ImageUtil.createCompatibleImage(image);
        }

        setToken((BufferedImage) image);
    } catch (UnsupportedFlavorException ufe) {
        ufe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    fireCompositionChanged();
}