Java Code Examples for java.awt.datatransfer.Transferable#getTransferData()

The following examples show how to use java.awt.datatransfer.Transferable#getTransferData() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
public void testClipboardCopy() throws IOException, ClassNotFoundException, UnsupportedFlavorException {
    DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String");

    FileObject fo = FileUtil.createData( testFileSystem.getRoot(), "dndtest.txt" );
    File tmpFile = FileUtil.toFile( fo );

    DataObject dob = DataObject.find( fo );
    DataNode node = new DataNode( dob, Children.LEAF );

    Transferable t = node.clipboardCopy();
    assertTrue( t.isDataFlavorSupported( DataFlavor.javaFileListFlavor ) );
    List fileList = (List) t.getTransferData( DataFlavor.javaFileListFlavor );
    assertNotNull( fileList );
    assertEquals( 1, fileList.size() );
    assertTrue( fileList.contains( tmpFile ) );

    assertTrue( t.isDataFlavorSupported( uriListFlavor ) );
    String uriList = (String) t.getTransferData( uriListFlavor );
    assertEquals( Utilities.toURI(tmpFile)+"\r\n", uriList );
}
 
Example 2
Source Project: darklaf   File: TabbedPaneTransferHandler.java    License: MIT License 6 votes vote down vote up
/**
 * Called when the drag-and-drop operation has just completed. This creates a new tab identical to the one
 * "dragged" and places it in the destination <code>JTabbedPane</code>.
 *
 * @param  c The component receiving the "drop" (the instance of
 *           <code>JTabbedPane</code>).
 * @param  t The data being transfered (information about the tab and the component contained by the tab).
 * @return   Whether or not the import was successful.
 */
@Override
public boolean importData(final JComponent c, final Transferable t) {

    boolean successful = false;
    if (hasTabFlavor(t.getTransferDataFlavors()) && mouseLocation != null) {
        try {
            JTabbedPane tabbedPane = (JTabbedPane) c;
            int tab = TabbedPaneUtil.getDroppedTabIndex(currentTransferable.getTabBounds(), tabbedPane,
                                                        supportsIndicator(tabbedPane), mouseLocation);
            TabTransferable.TabTransferData td = (TabTransferable.TabTransferData) t.getTransferData(tabFlavor);
            if (!TabbedPaneUtil.moveTabs(td.sourceTabbedPane, tabbedPane, td.tabIndex, tab)) {
                return true;
            }

            successful = true;
            DarkTabbedPaneUI ui = supportsIndicator(c);
            if (ui != null) {
                ui.clearDropIndicator();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return successful;
}
 
Example 3
private void checkClipBoard() {
	if(clipboard==null)
		clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	Transferable trans = clipboard.getContents(null);
	if (trans != null) {
		if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
			try {
				String text = (String) trans.getTransferData(DataFlavor.stringFlavor);
				if(!text.equals(lastPasteItem)){
					CMN.Log("剪贴板", text);
					etSearch.setText(text);
					lastPasteItem=text;
				}
			} catch (Exception e) {

			}
		}
	}
}
 
Example 4
Source Project: netbeans   File: ItemTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test of cut method, of class org.netbeans.modules.palette.Item.
 */
public void testCut() throws Exception {
    PaletteActions actions = new DummyActions();
    PaletteController pc = PaletteFactory.createPalette( getRootFolderName(), actions );
    Model model = pc.getModel();

    Category[] categories = model.getCategories();
    
    for( int i=0; i<categories.length; i++ ) {
        Item[] items = categories[i].getItems();
        for( int j=0; j<items.length; j++ ) {
            Transferable t = items[j].cut();
            assertNotNull( t );
            assertTrue( t.isDataFlavorSupported( PaletteController.ITEM_DATA_FLAVOR ) );
            Lookup lookup = (Lookup)t.getTransferData( PaletteController.ITEM_DATA_FLAVOR );
            assertNotNull( lookup );
            Node node = (Node)lookup.lookup( Node.class );
            assertEquals( itemNames[i][j], node.getName() );
        }
    }
}
 
Example 5
Source Project: netbeans   File: ItemTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test of drag method, of class org.netbeans.modules.palette.Item.
 */
public void testDrag() throws Exception {
    PaletteActions actions = new DummyActions();
    PaletteController pc = PaletteFactory.createPalette( getRootFolderName(), actions );
    Model model = pc.getModel();

    Category[] categories = model.getCategories();
    
    for( int i=0; i<categories.length; i++ ) {
        Item[] items = categories[i].getItems();
        for( int j=0; j<items.length; j++ ) {
            Transferable t = items[j].drag();
            assertNotNull( t );
            assertTrue( t.isDataFlavorSupported( PaletteController.ITEM_DATA_FLAVOR ) );
            Lookup lookup = (Lookup)t.getTransferData( PaletteController.ITEM_DATA_FLAVOR );
            assertNotNull( lookup );
            Node node = (Node)lookup.lookup( Node.class );
            assertEquals( itemNames[i][j], node.getName() );
        }
    }
}
 
Example 6
private String getBestCharsetForTextFormat(Long lFormat,
    Transferable localeTransferable) throws IOException
{
    String charset = null;
    if (localeTransferable != null &&
        isLocaleDependentTextFormat(lFormat) &&
        localeTransferable.isDataFlavorSupported(javaTextEncodingFlavor))
    {
        try {
            charset = new String(
                (byte[])localeTransferable.getTransferData(javaTextEncodingFlavor),
                "UTF-8"
            );
        } catch (UnsupportedFlavorException cannotHappen) {
        }
    } else {
        charset = getCharsetForTextFormat(lFormat);
    }
    if (charset == null) {
        // Only happens when we have a custom text type.
        charset = getDefaultTextCharset();
    }
    return charset;
}
 
Example 7
Source Project: lizzie   File: Utils.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean importData(JComponent comp, Transferable t) {
  try {
    Object o = t.getTransferData(DataFlavor.javaFileListFlavor);
    String filePath = o.toString();
    if (filePath.startsWith("[")) {
      filePath = filePath.substring(1);
    }
    if (filePath.endsWith("]")) {
      filePath = filePath.substring(0, filePath.length() - 1);
    }
    if (!(filePath.endsWith(".sgf") || filePath.endsWith(".gib"))) {
      return false;
    }
    File file = new File(filePath);
    Lizzie.frame.loadFile(file);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return true;
}
 
Example 8
private String getBestCharsetForTextFormat(Long lFormat,
    Transferable localeTransferable) throws IOException
{
    String charset = null;
    if (localeTransferable != null &&
        isLocaleDependentTextFormat(lFormat) &&
        localeTransferable.isDataFlavorSupported(javaTextEncodingFlavor))
    {
        try {
            charset = new String(
                (byte[])localeTransferable.getTransferData(javaTextEncodingFlavor),
                "UTF-8"
            );
        } catch (UnsupportedFlavorException cannotHappen) {
        }
    } else {
        charset = getCharsetForTextFormat(lFormat);
    }
    if (charset == null) {
        // Only happens when we have a custom text type.
        charset = getDefaultTextCharset();
    }
    return charset;
}
 
Example 9
Source Project: htmlunit   File: DoTypeProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private static String getClipboardContent() {
    String result = "";
    final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    final Transferable contents = clipboard.getContents(null);
    if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
            result = (String) contents.getTransferData(DataFlavor.stringFlavor);
        }
        catch (final UnsupportedFlavorException | IOException ex) {
        }
    }
    return result;
}
 
Example 10
Source Project: CXTouch   File: GUIUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return the text content on clipboard.
 */
public static String getClipText() {
    Transferable transfer = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    if (!transfer.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        return null;
    }
    String dataObj;
    try {
        dataObj = (String) transfer.getTransferData(DataFlavor.stringFlavor);
        return dataObj;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    }
}
 
Example 11
void checkImage(DropTargetDropEvent dtde) {
    final Transferable t = dtde.getTransferable();
    if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
        dtde.acceptDrop(DnDConstants.ACTION_COPY);
        Image im;
        try {
            im = (Image) t.getTransferData(DataFlavor.imageFlavor);
            System.err.println("getTransferData was successful");
        } catch (Exception e) {
            System.err.println("Can't getTransferData: " + e);
            dtde.dropComplete(false);
            notifyTransferSuccess(false);
            return;
        }

        if (im == null) {
            System.err.println("getTransferData returned null");
            dtde.dropComplete(false);
            notifyTransferSuccess(false);
        } else if (areImagesIdentical(image, im)) {
            dtde.dropComplete(true);
            notifyTransferSuccess(true);
        } else {
            System.err.println("transferred image is different from initial image");
            dtde.dropComplete(false);
            notifyTransferSuccess(false);
        }

    } else {
        System.err.println("imageFlavor is not supported by Transferable");
        dtde.rejectDrop();
        notifyTransferSuccess(false);
    }
}
 
Example 12
Source Project: netbeans   File: NodeTransfer.java    License: Apache License 2.0 5 votes vote down vote up
/** Obtain a node from a transferable.
* Probes the transferable in case it includes a flavor corresponding
* to a node operation (which you must specify a mask for).
*
* @param t transferable
* @param action one of the <code>DND_*</code> or <code>CLIPBOARD_*</code> constants
* @return the node or <code>null</code>
*/
public static Node node(Transferable t, int action) {
    DataFlavor[] flavors = t.getTransferDataFlavors();

    if (flavors == null) {
        return null;
    }

    int len = flavors.length;

    String subtype = "x-java-openide-nodednd"; // NOI18N
    String primary = "application"; // NOI18N
    String mask = "mask"; // NOI18N

    for (int i = 0; i < len; i++) {
        DataFlavor df = flavors[i];

        if (df.getSubType().equals(subtype) && df.getPrimaryType().equals(primary)) {
            try {
                int m = Integer.valueOf(df.getParameter(mask)).intValue();

                if ((m & action) != 0) {
                    // found the node
                    return (Node) t.getTransferData(df);
                }
            } catch (NumberFormatException nfe) {
                maybeReportException(nfe);
            } catch (ClassCastException cce) {
                maybeReportException(cce);
            } catch (IOException ioe) {
                maybeReportException(ioe);
            } catch (UnsupportedFlavorException ufe) {
                maybeReportException(ufe);
            }
        }
    }

    return null;
}
 
Example 13
Source Project: marathonv5   File: ListTransferHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean importData(TransferHandler.TransferSupport info) {
    if (!info.isDrop()) {
        return false;
    }

    JList list = (JList) info.getComponent();
    DefaultListModel listModel = (DefaultListModel) list.getModel();
    JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
    int index = dl.getIndex();
    boolean insert = dl.isInsert();

    // 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;
    }

    // Perform the actual import.
    if (insert) {
        listModel.add(index, data);
    } else {
        listModel.set(index, data);
    }
    return true;
}
 
Example 14
void checkImage(DropTargetDropEvent dtde) {
    final Transferable t = dtde.getTransferable();
    if (t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
        dtde.acceptDrop(DnDConstants.ACTION_COPY);
        Image im;
        try {
            im = (Image) t.getTransferData(DataFlavor.imageFlavor);
            System.err.println("getTransferData was successful");
        } catch (Exception e) {
            System.err.println("Can't getTransferData: " + e);
            dtde.dropComplete(false);
            notifyTransferSuccess(false);
            return;
        }

        if (im == null) {
            System.err.println("getTransferData returned null");
            dtde.dropComplete(false);
            notifyTransferSuccess(false);
        } else if (areImagesIdentical(image, im)) {
            dtde.dropComplete(true);
            notifyTransferSuccess(true);
        } else {
            System.err.println("transferred image is different from initial image");
            dtde.dropComplete(false);
            notifyTransferSuccess(false);
        }

    } else {
        System.err.println("imageFlavor is not supported by Transferable");
        dtde.rejectDrop();
        notifyTransferSuccess(false);
    }
}
 
Example 15
public static String getSystemClipboard() {
	Clipboard sysClb = null;
	sysClb = Toolkit.getDefaultToolkit().getSystemClipboard();
	try {
		Transferable t = sysClb.getContents(null);
		if (null != t && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
			String text = (String) t.getTransferData(DataFlavor.stringFlavor);
			return text;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 16
@Override
public boolean importData(TransferHandler.TransferSupport support) {
    if (!canImport(support)) {
        return false;
    }
    // Extract transfer data.
    DefaultMutableTreeNode[] nodes = null;
    try {
        Transferable t = support.getTransferable();
        nodes = (DefaultMutableTreeNode[]) t.getTransferData(nodesFlavor);
    } catch (UnsupportedFlavorException ufe) {
        System.out.println("UnsupportedFlavor: " + ufe.getMessage());
    } catch (java.io.IOException ioe) {
        System.out.println("I/O error: " + ioe.getMessage());
    }
    // Get drop location info.
    JTree.DropLocation dl = (JTree.DropLocation) support.getDropLocation();
    int childIndex = dl.getChildIndex();
    TreePath dest = dl.getPath();
    DefaultMutableTreeNode parent = (DefaultMutableTreeNode)
            dest.getLastPathComponent();
    JTree tree = (JTree) support.getComponent();
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    // Configure for drop mode.
    int index = childIndex;    // DropMode.INSERT
    if (childIndex == -1) {     // DropMode.ON
        index = parent.getChildCount();
    }
    // Add data to model.
    for (DefaultMutableTreeNode node : nodes) {
        model.insertNodeInto(node, parent, index++);
    }
    return true;
}
 
Example 17
Source Project: darklaf   File: TabFrameTransferHandler.java    License: MIT License 4 votes vote down vote up
/**
 * Called when the drag-and-drop operation has just completed. This creates a new tab identical to the one
 * "dragged" and places it in the destination <code>JTabbedPane</code>.
 *
 * @param  c The component receiving the "drop" (the instance of
 *           <code>JTabbedPane</code>).
 * @param  t The data being transfered (information about the tab and the component contained by the tab).
 * @return   Whether or not the import was successful.
 */
@Override
public boolean importData(final JComponent c, final Transferable t) {
    boolean successful = false;
    if (hasTabFlavor(t.getTransferDataFlavors()) && mouseLocation != null) {
        try {
            JTabFrame tabFrame = (JTabFrame) c;
            JTabFrame.TabFramePosition tab = getDropPosition(mouseLocation, tabFrame);
            Alignment a = tab.getAlignment();
            int index = tab.getIndex();
            TabTransferable.TabTransferData td = (TabTransferable.TabTransferData) t.getTransferData(tabFlavor);

            if (tabFrame == td.sourceTabFrame && td.tabAlignment == a) {
                if (index >= td.tabIndex) {
                    index--;
                }
            }
            index++;

            if (tabFrame == td.sourceTabFrame && a == td.tabAlignment && index == td.tabIndex) {
                // Nothing to do. Just select the tab to be sure.
                if (td.wasSelected) {
                    selectTab(td.sourceTabFrame, a, index);
                }
                return false;
            }
            if (a == null || index < 0 || index > tabFrame.getTabCountAt(a)) {
                return false;
            }
            TabFrameTab tabComp = td.sourceTabFrame.getTabComponentAt(td.tabAlignment, td.tabIndex);
            Component popupComp = td.sourceTabFrame.getPopupComponentAt(td.tabAlignment, td.tabIndex);
            td.sourceTabFrame.removeTab(td.tabAlignment, td.tabIndex);
            tabFrame.insertTab((TabFramePopup) popupComp, tabComp, a, index);
            if (td.wasSelected) {
                tabFrame.toggleTab(a, index, true);
            }
            SwingUtilities.invokeLater(() -> td.tab.getComponent().repaint());

            successful = true;
            TabFrameUI ui = getUI(c);
            if (ui != null) {
                ui.clearTargetIndicator();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return successful;
}
 
Example 18
Source Project: netbeans   File: EditorCaret.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void mouseClicked(MouseEvent evt) {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("EditorCaret.mouseClicked: " + logMouseEvent(evt) + ", state=" + mouseState + '\n'); // NOI18N
    }

    JTextComponent c = component;
    if (c != null) {
        if (evt.getClickCount() == 1 && evt.isControlDown() && evt.isShiftDown()) {
            evt.consume(); // consume event already handled by mousePressed
        }
        if (isMiddleMouseButtonExt(evt)) {
            if (evt.getClickCount() == 1) {
                if (c == null) {
                    return;
                }
                Clipboard buffer = component.getToolkit().getSystemSelection();

                if (buffer == null) {
                    return;
                }

                Transferable trans = buffer.getContents(null);
                if (trans == null) {
                    return;
                }

                final Document doc = c.getDocument();
                if (doc == null) {
                    return;
                }

                final int offset = c.getUI().viewToModel(c, new Point(evt.getX(), evt.getY()));

                try {
                    final String pastingString = (String) trans.getTransferData(DataFlavor.stringFlavor);
                    if (pastingString == null) {
                        return;
                    }
                    Runnable pasteRunnable = new Runnable() {
                        public @Override
                        void run() {
                            try {
                                doc.insertString(offset, pastingString, null);
                                setDot(offset + pastingString.length());
                                setMagicCaretPosition(null);
                            } catch (BadLocationException exc) {
                            }
                        }
                    };
                    AtomicLockDocument ald = LineDocumentUtils.as(doc, AtomicLockDocument.class);
                    if (ald != null) {
                        ald.runAtomic(pasteRunnable);
                    } else {
                        pasteRunnable.run();
                    }
                } catch (UnsupportedFlavorException ufe) {
                } catch (IOException ioe) {
                }
            }
        }
    }
}
 
Example 19
@Override
public Object translateBytes(byte[] bytes, DataFlavor flavor, long format,
    Transferable localeTransferable) throws IOException
{


    if (format == CF_FILEGROUPDESCRIPTORA || format == CF_FILEGROUPDESCRIPTORW) {
        if (bytes == null || !DataFlavor.javaFileListFlavor.equals(flavor)) {
            throw new IOException("data translation failed");
        }
        String st = new String(bytes, 0, bytes.length, "UTF-16LE");
        String[] filenames = st.split("\0");
        if( 0 == filenames.length ){
            return null;
        }

        // Convert the strings to File objects
        File[] files = new File[filenames.length];
        for (int i = 0; i < filenames.length; ++i) {
            files[i] = new File(filenames[i]);
            //They are temp-files from memory Stream, so they have to be removed on exit
            files[i].deleteOnExit();
        }
        // Turn the list of Files into a List and return
        return Arrays.asList(files);
    }

    if (format == CFSTR_INETURL &&
            URL.class.equals(flavor.getRepresentationClass()))
    {
        String charset = getDefaultTextCharset();
        if (localeTransferable != null && localeTransferable.
                                                                isDataFlavorSupported(javaTextEncodingFlavor))
        {
            try {
                charset = new String((byte[])localeTransferable.
                    getTransferData(javaTextEncodingFlavor), "UTF-8");
            } catch (UnsupportedFlavorException cannotHappen) {
            }
        }
        return new URL(new String(bytes, charset));
    }

    return super.translateBytes(bytes , flavor, format,
                                    localeTransferable);

}
 
Example 20
/**
 * Convenience function to try to get a {@code TradeRouteCargoLabel}
 * from a {@code Transferable}.
 *
 * @param data The {@code Transferable} to query.
 * @return The label found if any.
 * @exception IOException if the data is not available.
 * @exception UnsupportedFlavorException on flavor mismatch.
 */
private TradeRouteCargoLabel tryTransfer(Transferable data)
    throws IOException, UnsupportedFlavorException {
    return (TradeRouteCargoLabel)data.getTransferData(DefaultTransferHandler.flavor);
}