Example usage for java.awt.datatransfer Transferable getTransferData

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

Introduction

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

Prototype

public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException;

Source Link

Document

Returns an object which represents the data to be transferred.

Usage

From source file:org.apache.jmeter.gui.MainFrame.java

public boolean openJmxFilesFromDragAndDrop(Transferable tr) throws UnsupportedFlavorException, IOException {
    @SuppressWarnings("unchecked")
    List<File> files = (List<File>) tr.getTransferData(DataFlavor.javaFileListFlavor);
    if (files.isEmpty()) {
        return false;
    }//from w  ww.j a  v a  2s  . c om
    File file = files.get(0);
    if (!file.getName().endsWith(".jmx")) {
        log.warn("Importing file:" + file.getName()
                + "from DnD failed because file extension does not end with .jmx");
        return false;
    }

    ActionEvent fakeEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ActionNames.OPEN);
    LoadDraggedFile.loadProject(fakeEvent, file);

    return true;
}

From source file:org.freeplane.features.clipboard.mindmapmode.MClipboardController.java

private IDataFlavorHandler getFlavorHandler(final Transferable t) {
    if (t.isDataFlavorSupported(MindMapNodesSelection.mindMapNodesFlavor)) {
        try {//from  w w  w.  j  a v  a  2  s.  co  m
            final String textFromClipboard = t.getTransferData(MindMapNodesSelection.mindMapNodesFlavor)
                    .toString();
            return new MindMapNodesFlavorHandler(textFromClipboard);
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    if (t.isDataFlavorSupported(MindMapNodesSelection.fileListFlavor)) {
        try {
            final List<File> fileList = castToFileList(t.getTransferData(MindMapNodesSelection.fileListFlavor));
            if (!shouldIgnoreFileListFlavor(fileList))
                return new FileListFlavorHandler(fileList);
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    final ResourceController resourceController = ResourceController.getResourceController();
    if (t.isDataFlavorSupported(MindMapNodesSelection.htmlFlavor)) {
        try {
            final String textFromClipboard = t.getTransferData(MindMapNodesSelection.htmlFlavor).toString();
            if (textFromClipboard.charAt(0) != 65533) {
                if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    final MTextController textController = (MTextController) TextController.getController();
                    final boolean richText = textController
                            .useRichTextInEditor(RESOURCES_REMIND_USE_RICH_TEXT_IN_NEW_NODES);
                    if (richText) {
                        final boolean structuredHtmlImport = resourceController
                                .getBooleanProperty("structured_html_import");
                        final IDataFlavorHandler htmlFlavorHandler;
                        if (structuredHtmlImport) {
                            htmlFlavorHandler = new StructuredHtmlFlavorHandler(textFromClipboard);
                        } else {
                            htmlFlavorHandler = new DirectHtmlFlavorHandler(textFromClipboard);
                        }
                        return htmlFlavorHandler;
                    }
                }
            }
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
            final String plainTextFromClipboard = t.getTransferData(DataFlavor.stringFlavor).toString();
            return new StringFlavorHandler(plainTextFromClipboard);
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
        try {
            BufferedImage image = (BufferedImage) t.getTransferData(DataFlavor.imageFlavor);
            return new ImageFlavorHandler(image);
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    return null;
}

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

/**
 * Creates a new WorkSpace object./*  w w w .  j  a  v  a2s  . c o m*/
 */
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:xtrememp.PlaylistManager.java

@Override
@SuppressWarnings("unchecked")
public void drop(DropTargetDropEvent ev) {
    DropTargetContext targetContext = ev.getDropTargetContext();
    Transferable t = ev.getTransferable();
    try {// w w w.j av a  2  s  . c o m
        // Windows
        if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            ev.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            addFiles((List<File>) t.getTransferData(DataFlavor.javaFileListFlavor), false);
            targetContext.dropComplete(true);
            // Linux
        } else if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            ev.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            String urls = (String) t.getTransferData(DataFlavor.stringFlavor);
            List<File> fileList = new ArrayList<>();
            StringTokenizer st = new StringTokenizer(urls);
            while (st.hasMoreTokens()) {
                URI uri = new URI(st.nextToken());
                fileList.add(new File(uri));
            }
            addFiles(fileList, false);
            targetContext.dropComplete(true);
        }
    } catch (UnsupportedFlavorException | InvalidDnDOperationException | IOException | URISyntaxException ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:kolacer.Kolacer.java

private String stringZeSchranky() {
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable t = c.getContents(this);
    if (t == null)
        return null;
    try {//from w w w . j ava  2 s .co  m
        return ((String) t.getTransferData(DataFlavor.stringFlavor));
    } catch (UnsupportedFlavorException | IOException e) {
        System.err.println(e.getMessage());
        return "Chyba pi ?ten ze schrnky";
    } //try
}

From source file:org.rimudb.editor.DescriptorEditor.java

/**
 * Build the panel//from   w  w  w  .j  a  va  2s.  c om
 */
private JPanel createColumnTablePanel() {
    JPanel columnPanel = new JPanel();
    columnPanel.setLayout(new BoxLayout(columnPanel, BoxLayout.Y_AXIS));

    // Create the property table panel
    propertyModel = new PropertyTableModel();

    // Add a listener to set the changed state
    propertyModel.addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            markChanged();

            if (e instanceof PropertyTableModelEvent) {
                PropertyTableModelEvent ptme = (PropertyTableModelEvent) e;

                // If the columnName column was changed then check it isn't
                // a PK
                if (ptme.getColumn() == 1) {

                    String beforeColumnName = (String) ptme.getBeforeValue();
                    String afterColumnName = (String) ptme.getAfterValue();

                    // Is the field entry in the list of primary keys?
                    for (int i = 0; i < pkListModel.getSize(); i++) {
                        String pkColumnName = (String) pkListModel.get(i);
                        // If it's found then remove it
                        if (beforeColumnName.equals(pkColumnName)) {
                            pkListModel.set(i, afterColumnName);
                            break;
                        }
                    }

                }

            }
        }
    });

    table = new ATable(getPropertyModel());
    table.setName("ColumnTable");
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            int selectedRowCount = table.getSelectedRowCount();
            removeColumnBtn.setEnabled(selectedRowCount > 0);
            moveUpBtn.setEnabled(selectedRowCount > 0);
            moveDownBtn.setEnabled(selectedRowCount > 0);
        }
    });
    table.setTransferHandler(new TransferHandler() {

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(JComponent c) {
            ATable columnTable = (ATable) c;
            int row = columnTable.getSelectedRow();
            String columnName = getPropertyModel().getRow(row).getColumnName();
            return new StringSelection(columnName);
        }
    });
    table.setDragEnabled(true);

    JScrollPane sp = new JScrollPane(table);
    sp.setMaximumSize(new Dimension(Short.MAX_VALUE, 325));
    sp.setPreferredSize(new Dimension(Short.MAX_VALUE, 325));
    sp.setMinimumSize(new Dimension(Short.MAX_VALUE, 325));

    JComboBox typeCB = new JComboBox(DatabaseTypes.getAllTypes());
    typeCB.setEditable(false);

    javax.swing.table.TableColumn typeColumn = table.getColumnModel().getColumn(2);
    typeColumn.setCellEditor(new DefaultCellEditor(typeCB));

    // Create the popup menu and set it on the table
    propertyPopup = new TablePopupMenu(this, table);
    table.addMouseListener(propertyPopup);
    sp.addMouseListener(propertyPopup);
    sp.setAlignmentX(LEFT_ALIGNMENT);

    columnPanel.add(sp);

    columnPanel.add(Box.createVerticalStrut(10));

    JLabel pkLabel = new JLabel("Primary Key Columns", SwingConstants.LEFT);
    pkLabel.setAlignmentX(LEFT_ALIGNMENT);
    columnPanel.add(pkLabel);

    pkListModel = new DefaultListModel();
    pkListModel.addListDataListener(new ListDataListener() {
        public void intervalRemoved(ListDataEvent e) {
            markChanged();
        }

        public void intervalAdded(ListDataEvent e) {
            markChanged();
        }

        public void contentsChanged(ListDataEvent e) {
            markChanged();
        }
    });

    pkList = new JList(pkListModel);
    pkList.setName("pkList");
    pkList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    pkList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            int selectedRowCount = pkList.getSelectedIndex();
            removePkBtn.setEnabled(selectedRowCount > -1);
        }
    });
    pkList.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            }
            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            DefaultListModel listModel = (DefaultListModel) pkList.getModel();
            int index = dl.getIndex();

            // Get the string that is being dropped.
            Transferable t = info.getTransferable();
            String data;
            try {
                data = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            // If this is a copy action then check we don't already have that String
            if (info.getDropAction() == COPY && listModel.indexOf(data) > -1) {
                displayDropLocation("The column " + data + " is already a primary key");
                return false;
            }

            // Perform the actual import. 
            if (dl.isInsert()) {
                int oldIndex = listModel.indexOf(data);
                if (oldIndex < index) {
                    listModel.add(index, data);
                    listModel.remove(oldIndex);
                } else {
                    listModel.remove(oldIndex);
                    listModel.add(index, data);
                }
            } else {
                // Don't handle replacements
            }
            return true;
        }

        public int getSourceActions(JComponent c) {
            return MOVE;
        }

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            Object[] values = list.getSelectedValues();

            StringBuffer buff = new StringBuffer();

            for (int i = 0; i < values.length; i++) {
                Object val = values[i];
                buff.append(val == null ? "" : val.toString());
                if (i != values.length - 1) {
                    buff.append("\n");
                }
            }
            return new StringSelection(buff.toString());
        }
    });
    pkList.setDropMode(DropMode.INSERT);
    pkList.setDragEnabled(true);

    JScrollPane pkScrollPanel = new JScrollPane(pkList);
    pkScrollPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 100));
    pkScrollPanel.setAlignmentX(LEFT_ALIGNMENT);

    columnPanel.add(pkScrollPanel);

    return columnPanel;
}

From source file:org.freeplane.features.clipboard.mindmapmode.MClipboardController.java

private void processTransferable(final Transferable transferable, final NodeModel target, Operation operation) {
    if (!transferable.isDataFlavorSupported(MindMapNodesSelection.mindMapNodeObjectsFlavor))
        return;/*from  ww  w  .  ja  va  2  s .  c o m*/
    try {
        @SuppressWarnings("unchecked")
        final List<NodeModel> clonedNodes = (List<NodeModel>) transferable
                .getTransferData(MindMapNodesSelection.mindMapNodeObjectsFlavor);
        for (NodeModel clonedNode : clonedNodes) {
            if (clonedNode.getParentNode() == null || !clonedNode.getMap().equals(target.getMap()))
                return;
            final MMapController mapController = (MMapController) Controller.getCurrentModeController()
                    .getMapController();
            if (!clonedNode.isRoot() && !clonedNode.subtreeContainsCloneOf(target)) {
                switch (operation) {
                case CLONE:
                    final NodeModel clone = clonedNode.cloneTree();
                    mapController.addNewNode(clone, target, target.getChildCount(), target.isNewChildLeft());
                    break;
                case MOVE:
                    mapController.moveNodeAsChild(clonedNode, target, target.isNewChildLeft(),
                            target.isNewChildLeft() != clonedNode.isLeft());
                    break;
                }
            }
        }
    } catch (Exception e) {
        LogUtils.severe(e);
    }
}

From source file:plugin.notes.gui.NotesTreeNode.java

/**
 * handles a drop of a java file list//from ww w. j a  v a 2s . co m
 *
 * @param dtde
 *          drop target drop even - a java dile list has been dropped on
 *          something that represents this node.
 * @return returns true if the drop takes place, false if not
 */
public boolean handleDropJavaFileList(DropTargetDropEvent dtde) {
    dtde.acceptDrop(dtde.getDropAction());

    Transferable t = dtde.getTransferable();

    try {
        List fileList = ((List) t.getTransferData(DataFlavor.javaFileListFlavor));

        for (Object aFileList : fileList) {
            File newFile = (File) aFileList;

            if (newFile.exists()) {

                FileUtils.copyFile(newFile,
                        new File(dir.getAbsolutePath() + File.separator + newFile.getName()));
            }
        }
    } catch (Exception e) {
        Logging.errorPrint(e.getMessage(), e);

        return false;
    }

    return true;
}

From source file:DragDropTreeExample.java

protected boolean dropFile(int action, Transferable transferable, Point location)
        throws IOException, UnsupportedFlavorException, MalformedURLException {
    List files = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
    TreePath treePath = tree.getPathForLocation(location.x, location.y);
    File targetDirectory = findTargetDirectory(location);
    if (treePath == null || targetDirectory == null) {
        return false;
    }/*ww  w. j a v  a 2s.  c  om*/
    FileTree.FileTreeNode node = (FileTree.FileTreeNode) treePath.getLastPathComponent();

    // Highlight the drop location while we perform the drop
    tree.setSelectionPath(treePath);

    // Get File objects for all files being
    // transferred, eliminating duplicates.
    File[] fileList = getFileList(files);

    // Don't overwrite files by default
    copyOverExistingFiles = false;

    // Copy or move each source object to the target
    for (int i = 0; i < fileList.length; i++) {
        File f = fileList[i];
        if (f.isDirectory()) {
            transferDirectory(action, f, targetDirectory, node);
        } else {
            try {
                transferFile(action, fileList[i], targetDirectory, node);
            } catch (IllegalStateException e) {
                // Cancelled by user
                return false;
            }
        }
    }

    return true;
}

From source file:org.freeplane.features.clipboard.mindmapmode.MClipboardController.java

Collection<IDataFlavorHandler> getFlavorHandlers() {
    final Transferable t = getClipboardContents();
    final Collection<IDataFlavorHandler> handlerList = new LinkedList<IDataFlavorHandler>();
    if (t == null) {
        return handlerList;
    }/*  w ww  .j av  a2  s  .co m*/
    if (t.isDataFlavorSupported(MindMapNodesSelection.mindMapNodesFlavor)) {
        try {
            final String textFromClipboard = t.getTransferData(MindMapNodesSelection.mindMapNodesFlavor)
                    .toString();
            handlerList.add(new MindMapNodesFlavorHandler(textFromClipboard));
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    if (t.isDataFlavorSupported(MindMapNodesSelection.htmlFlavor)) {
        try {
            final String textFromClipboard = t.getTransferData(MindMapNodesSelection.htmlFlavor).toString();
            if (textFromClipboard.charAt(0) != 65533) {
                if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    handlerList.add(new StructuredHtmlFlavorHandler(textFromClipboard));
                    handlerList.add(new DirectHtmlFlavorHandler(textFromClipboard));
                }
            }
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
            final String plainTextFromClipboard = t.getTransferData(DataFlavor.stringFlavor).toString();
            handlerList.add(new StringFlavorHandler(plainTextFromClipboard));
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    if (t.isDataFlavorSupported(MindMapNodesSelection.fileListFlavor)) {
        try {
            final List<File> fileList = castToFileList(t.getTransferData(MindMapNodesSelection.fileListFlavor));
            handlerList.add(new FileListFlavorHandler(fileList));
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
        try {
            BufferedImage image = (BufferedImage) t.getTransferData(DataFlavor.imageFlavor);
            handlerList.add(new ImageFlavorHandler(image));
        } catch (final UnsupportedFlavorException e) {
        } catch (final IOException e) {
        }
    }
    return handlerList;
}