Example usage for java.awt.datatransfer Transferable getTransferDataFlavors

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

Introduction

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

Prototype

public DataFlavor[] getTransferDataFlavors();

Source Link

Document

Returns an array of DataFlavor objects indicating the flavors the data can be provided in.

Usage

From source file:org.feistymeow.dragdrop.ListTransferable.java

/**
 * checks if the transferable is appropriate to try to use as a java Reader.
 *//*  w  w w  .ja v  a2  s  . co m*/
public static boolean checkReaderFlavor(Transferable tran) {
    if (tran == null)
        return false;
    DataFlavor[] flavors = tran.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
        if (flavors[i].isRepresentationClassReader())
            return true;
    }
    return false;
}

From source file:org.feistymeow.dragdrop.ListTransferable.java

/**
 * Use a Reader to handle an incoming transferable.
 *///from  w  w  w .  ja v  a2s.c  o  m
public static List<Object> processReaderFlavor(Transferable tran) {
    if (tran == null)
        return null;
    logger.debug("trying URI list flavor.");
    DataFlavor[] flavors = tran.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
        if (flavors[i].isRepresentationClassReader()) {
            // it looks like we can work with this flavor just fine.
            logger.debug("found a reader flavor.");
            try {
                Reader reader = flavors[i].getReaderForText(tran);
                BufferedReader br = new BufferedReader(reader);
                return createFileArray(br);
            } catch (Throwable cause) {
                logger.debug("failed to scan reader for file list.");
            }
        }
    }
    return new ArrayList<Object>();
}

From source file:org.fife.ui.rtextarea.RTATextTransferHandler.java

/**
 * This method causes a transfer to a component from a clipboard or a 
 * DND drop operation.  The Transferable represents the data to be
 * imported into the component.  //from ww  w .j  a  va  2  s  .c o  m
 *
 * @param comp  The component to receive the transfer.  This
 *  argument is provided to enable sharing of TransferHandlers by
 *  multiple components.
 * @param t The data to import
 * @return <code>true</code> iff the data was inserted into the component.
 */
@Override
public boolean importData(JComponent comp, Transferable t) {

    JTextComponent c = (JTextComponent) comp;
    withinSameComponent = c == exportComp;

    // if we are importing to the same component that we exported from
    // then don't actually do anything if the drop location is inside
    // the drag location and set shouldRemove to false so that exportDone
    // knows not to remove any data
    if (withinSameComponent && c.getCaretPosition() >= p0 && c.getCaretPosition() <= p1) {
        shouldRemove = false;
        return true;
    }

    boolean imported = false;
    DataFlavor importFlavor = getImportFlavor(t.getTransferDataFlavors(), c);
    if (importFlavor != null) {
        try {
            InputContext ic = c.getInputContext();
            if (ic != null)
                ic.endComposition();
            Reader r = importFlavor.getReaderForText(t);
            handleReaderImport(r, c);
            imported = true;
        } catch (UnsupportedFlavorException ufe) {
            ufe.printStackTrace();
        } catch (BadLocationException ble) {
            ble.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    return imported;

}

From source file:org.gtdfree.GTDFree.java

protected TrayIcon getTrayIcon() {
    if (trayIcon == null) {
        if (ApplicationHelper.isGTKLaF()) {
            trayIcon = new TrayIcon(ApplicationHelper.loadImage(ApplicationHelper.icon_name_large_tray_splash));
        } else {/*w  w w.  jav  a2 s.c  om*/
            trayIcon = new TrayIcon(ApplicationHelper.loadImage(ApplicationHelper.icon_name_small_tray_splash));
        }

        trayIcon.setImageAutoSize(true);
        trayIcon.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    trayIconPopup.setVisible(false);
                    if (getJFrame().isVisible()) {
                        getJFrame().setVisible(false);
                    } else {
                        pushVisible();
                    }
                } else {
                    if (trayIconPopup.isVisible()) {
                        trayIconPopup.setVisible(false);
                    } else {
                        Point p = new Point(e.getPoint());
                        /*
                         * Disabled, because we are anyway doing things like rollover,
                         * which are probably done by Frame.
                        if (getJFrame().isShowing()) {
                           SwingUtilities.convertPointFromScreen(p, getJFrame());
                           trayIconPopup.show(getJFrame(), p.x, p.y);
                        } else {
                        }*/
                        trayIconPopup.show(null, p.x, p.y);
                    }
                }
            }
        });
        trayIcon.setToolTip("GTD-Free - " + Messages.getString("GTDFree.Tray.desc")); //$NON-NLS-1$ //$NON-NLS-2$

        /*
         * Necessary only when popup is showing with null window. Hides popup.
         */
        MouseListener hideMe = new MouseAdapter() {
            @Override
            public void mouseExited(MouseEvent e) {
                if (e.getComponent() instanceof JMenuItem) {
                    JMenuItem jm = (JMenuItem) e.getComponent();
                    jm.getModel().setRollover(false);
                    jm.getModel().setArmed(false);
                    jm.repaint();
                }

                Point p = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), trayIconPopup);
                //System.out.println(p.x+" "+p.y+" "+trayIconPopup.getWidth()+" "+trayIconPopup.getHeight());
                if (p.x < 0 || p.x >= trayIconPopup.getWidth() || p.y < 0 || p.y >= trayIconPopup.getHeight()) {
                    trayIconPopup.setVisible(false);
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                if (e.getComponent() instanceof JMenuItem) {
                    JMenuItem jm = (JMenuItem) e.getComponent();
                    jm.getModel().setRollover(true);
                    jm.getModel().setArmed(true);
                    jm.repaint();
                }
            }
        };

        trayIconPopup = new JPopupMenu();
        trayIconPopup.addMouseListener(hideMe);

        JMenuItem mi = new JMenuItem(Messages.getString("GTDFree.Tray.Drop")); //$NON-NLS-1$
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_small_collecting));
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Drop.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);

        /*
         * Workaround for tray, if JFrame is showing, then mouse click is not fired
         */
        mi.addMouseListener(new MouseAdapter() {
            private boolean click = false;

            @Override
            public void mousePressed(MouseEvent e) {
                click = true;
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (click) {
                    click = false;
                    doMouseClicked(e);
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                click = false;
            }

            private void doMouseClicked(MouseEvent e) {
                trayIconPopup.setVisible(false);
                Clipboard c = null;
                if (e.getButton() == MouseEvent.BUTTON1) {
                    c = Toolkit.getDefaultToolkit().getSystemClipboard();
                } else if (e.getButton() == MouseEvent.BUTTON2) {
                    c = Toolkit.getDefaultToolkit().getSystemSelection();
                } else {
                    return;
                }
                try {
                    Object o = c.getData(DataFlavor.stringFlavor);
                    if (o != null) {
                        getEngine().getGTDModel().collectAction(o.toString());
                    }
                    flashMessage(Messages.getString("GTDFree.Tray.Collect.ok"), e.getLocationOnScreen()); //$NON-NLS-1$
                } catch (Exception e1) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e1); //$NON-NLS-1$
                    flashMessage(Messages.getString("GTDFree.Tray.Collect.fail") + e1.getMessage(), //$NON-NLS-1$
                            e.getLocationOnScreen());
                }
            }
        });

        TransferHandler th = new TransferHandler() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
                return DataFlavor.selectBestTextFlavor(transferFlavors) != null;
            }

            @Override
            public boolean importData(JComponent comp, Transferable t) {
                try {
                    DataFlavor f = DataFlavor.selectBestTextFlavor(t.getTransferDataFlavors());
                    Object o = t.getTransferData(f);
                    if (o != null) {
                        getEngine().getGTDModel().collectAction(o.toString());
                    }
                    return true;
                } catch (UnsupportedFlavorException e) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$
                } catch (IOException e) {
                    Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$
                }
                return false;
            }

        };
        mi.setTransferHandler(th);

        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_large_delete));
        mi.setText(Messages.getString("GTDFree.Tray.Hide")); //$NON-NLS-1$
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Hide.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                if (getJFrame().isVisible()) {
                    getJFrame().setVisible(false);
                }
            }
        });
        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_small_splash));
        mi.setText(Messages.getString("GTDFree.Tray.Show")); //$NON-NLS-1$
        mi.setToolTipText(Messages.getString("GTDFree.Tray.Show.desc")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                pushVisible();
            }
        });
        trayIconPopup.add(mi);

        mi = new JMenuItem();
        mi.setIcon(ApplicationHelper.getIcon(ApplicationHelper.icon_name_large_exit));
        mi.setText(Messages.getString("GTDFree.Tray.Exit")); //$NON-NLS-1$
        mi.addMouseListener(hideMe);
        mi.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                trayIconPopup.setVisible(false);
                close(false);
            }
        });
        trayIconPopup.add(mi);

    }
    return trayIcon;
}

From source file:org.jas.dnd.DraggedObjectPictureGenerator.java

@Override
public DraggedObject get(Transferable transferable) {
    DataFlavor[] flavors = transferable.getTransferDataFlavors();
    if (flavors == null) {
        return null;
    }//w  w w . j  a  va2s  . c  om
    for (DataFlavor flavor : flavors) {
        List<File> files = null;
        files = tryGetFile(transferable, flavor);
        if (files != null && files.size() == 1 && !files.get(0).isDirectory()) {
            try {
                Object draggedObject = new Picture(files.get(0));
                return new SimpleDraggedObject(draggedObject);
            } catch (Exception e) {
                LOG.error(e, e);
            }
        }
    }
    return new SimpleDraggedObject(null);
}

From source file:org.kuali.test.ui.dnd.RepositoryDropTargetAdapter.java

@Override
public void drop(DropTargetDropEvent dtde) {
    boolean success = false;
    try {//from  www .j  av a 2  s  . com
        if (canDrop(dtde)) {
            Transferable t = dtde.getTransferable();
            Object data = t.getTransferData(t.getTransferDataFlavors()[0]);
            DefaultMutableTreeNode dropNode = getNodeAtPoint(dtde.getLocation());
            if ((dropNode != null) && (data != null) && (data instanceof RepositoryTransferData)) {
                repositoryTree.handleDataDrop(t.getTransferDataFlavors()[0], (RepositoryTransferData) data,
                        dropNode);
                success = true;
                dtde.dropComplete(true);
            }
        }
    }

    catch (Exception e) {
        LOG.error(e.toString(), e);
    }

    if (!success) {
        dtde.rejectDrop();
    }
}

From source file:org.wings.STransferHandler.java

/**
 * Imports the data specified in the Transferable into the given component
 * @param component/*from w  w  w.  j a v a 2  s .  c o  m*/
 * @param transferable
 * @return
 */
public boolean importData(SComponent component, Transferable transferable) {
    PropertyDescriptor propertyDecsriptor = getPropertyDescriptor(this.propertyName, component);
    if (propertyDecsriptor == null)
        return false;
    Method writeMethod = propertyDecsriptor.getWriteMethod();
    if (writeMethod == null)
        return false;
    Class<?>[] arguments = writeMethod.getParameterTypes();
    if (arguments == null || arguments.length != 1) {
        return false;
    }

    DataFlavor flavor = getPropertyDataFlavor(arguments[0], transferable.getTransferDataFlavors());
    if (flavor != null) {
        try {
            Object value = transferable.getTransferData(flavor);

            STransferHandler.invoke(writeMethod, component, new Object[] { value });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:tk.tomby.tedit.core.Workspace.java

/**
 * Creates a new WorkSpace object./*from  w w  w. ja  va  2 s .com*/
 */
public Workspace() {
    super();

    setLayout(new BorderLayout());
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    MessageManager.addMessageListener(MessageManager.BUFFER_GROUP_NAME, new IMessageListener<BufferMessage>() {
        public void receiveMessage(BufferMessage message) {
            Workspace.this.receiveMessage(message);
        }
    });

    MessageManager.addMessageListener(MessageManager.PREFERENCE_GROUP_NAME,
            new IMessageListener<PreferenceMessage>() {
                public void receiveMessage(PreferenceMessage message) {
                    Workspace.this.receiveMessage(message);
                }
            });

    bufferPane = new JTabbedPane();
    bufferPane.setMinimumSize(new Dimension(600, 400));
    bufferPane.setPreferredSize(new Dimension(800, 600));
    bufferPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

    bottomPort = createDockingPort(0, 80);
    rightPort = createDockingPort(80, 0);
    leftPort = createDockingPort(80, 0);

    splitPaneRight = createSplitPane(JSplitPane.HORIZONTAL_SPLIT, bufferPane, rightPort);
    splitPaneLeft = createSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPort, splitPaneRight);
    splitPaneBottom = createSplitPane(JSplitPane.VERTICAL_SPLIT, splitPaneLeft, bottomPort);

    bufferPane.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent evt) {
            MessageManager
                    .sendMessage(new WorkspaceMessage(evt.getSource(), bufferPane.getSelectedComponent()));
        }
    });

    bufferPane.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent evt) {
            if (evt.getClickCount() == 2) {
                splitPaneLeft.setDividerLocation(0.0d);
                splitPaneBottom.setDividerLocation(1.0d);
                splitPaneRight.setDividerLocation(1.0d);
            }
        }
    });

    DropTarget dropTarget = new DropTarget(bufferPane, new DropTargetAdapter() {
        public void drop(DropTargetDropEvent dtde) {
            if (log.isDebugEnabled()) {
                log.debug("drop start");
            }

            try {
                if (log.isDebugEnabled()) {
                    log.debug(dtde.getSource());
                }

                Transferable tr = dtde.getTransferable();
                DataFlavor[] flavors = tr.getTransferDataFlavors();

                for (int i = 0; i < flavors.length; i++) {
                    DataFlavor flavor = flavors[i];

                    if (log.isDebugEnabled()) {
                        log.debug("mime-type:" + flavor.getMimeType());
                    }

                    if (flavor.isMimeTypeEqual("text/plain")) {
                        final Object obj = tr.getTransferData(flavor);

                        if (log.isDebugEnabled()) {
                            log.debug(obj);
                        }

                        if (obj instanceof String) {
                            TaskManager.execute(new Runnable() {
                                public void run() {
                                    BufferFactory factory = new BufferFactory();
                                    IBuffer buffer = factory.createBuffer();
                                    buffer.open((String) obj);

                                    addBuffer(buffer);
                                }
                            });
                        }

                        dtde.dropComplete(true);

                        return;
                    }
                }
            } catch (UnsupportedFlavorException e) {
                log.warn(e.getMessage(), e);
            } catch (IOException e) {
                log.warn(e.getMessage(), e);
            }

            dtde.rejectDrop();

            if (log.isDebugEnabled()) {
                log.debug("drop end");
            }
        }
    });

    bufferPane.setDropTarget(dropTarget);

    this.add(BorderLayout.CENTER, splitPaneBottom);
}

From source file:zsk.JFCMainClient.java

/**
 * processing event of dropping a HTTP URL, YT-Video Image or plain text (URL) onto the frame
 * /*from  w  ww  . j  a  v a2  s. c o m*/
 * seems not to work with M$-IE (8,9) - what a pity!
 */
public void drop(DropTargetDropEvent dtde) {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    DataFlavor fl = null;
    String str = "";

    debugoutput("DataFlavors found: ".concat(Integer.toString(flavors.length)));
    for (int i = 0; i < flavors.length; i++) {
        fl = flavors[i];
        if (fl.isFlavorTextType() /* || fl.isMimeTypeEqual("text/html") || fl.isMimeTypeEqual("application/x-java-url") || fl.isMimeTypeEqual("text/uri-list")*/) {
            try {
                dtde.acceptDrop(dtde.getDropAction());
            } catch (Throwable t) {
            }
            try {
                if (tr.getTransferData(fl) instanceof InputStreamReader) {
                    debugoutput("Text-InputStream");
                    BufferedReader textreader = new BufferedReader((Reader) tr.getTransferData(fl));
                    String sline = "";
                    try {
                        while (sline != null) {
                            sline = textreader.readLine();
                            if (sline != null)
                                str += sline;
                        }
                    } catch (Exception e) {
                    } finally {
                        textreader.close();
                    }
                    str = str.replaceAll("<[^>]*>", ""); // remove HTML tags, especially a hrefs - ignore HTML characters like &szlig; (which are no tags)
                } else if (tr.getTransferData(fl) instanceof InputStream) {
                    debugoutput("Byte-InputStream");
                    InputStream input = new BufferedInputStream((InputStream) tr.getTransferData(fl));
                    int idata = input.read();
                    String sresult = "";
                    while (idata != -1) {
                        if (idata != 0)
                            sresult += new Character((char) idata).toString();
                        idata = input.read();
                    } // while
                    debugoutput("sresult: ".concat(sresult));
                } else {
                    str = tr.getTransferData(fl).toString();
                }
            } catch (IOException ioe) {
            } catch (UnsupportedFlavorException ufe) {
            }

            debugoutput("drop event text: ".concat(str).concat(" (").concat(fl.getMimeType()).concat(") "));
            // insert text into textfield - almost the same as user drops text/url into this field
            // except special characaters -> from http://de.wikipedia.org/wiki/GNU-Projekt (GNU is not Unix)(&bdquo;GNU is not Unix&ldquo;)
            // two drops from same source .. one time in textfield and elsewhere - maybe we change that later?!
            if (str.matches(szYTREGEX.concat("(.*)"))) {
                synchronized (JFCMainClient.frame.textinputfield) {
                    JFCMainClient.frame.textinputfield
                            .setText(str.concat(JFCMainClient.frame.textinputfield.getText()));
                }
                debugoutput("breaking for-loop with str: ".concat(str));
                break;
            }
        } else {
            String sv = "drop event unknown type: ".concat(fl.getHumanPresentableName());
            //output(sv);
            debugoutput(sv);
        }
    } // for

    dtde.dropComplete(true);
}