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

The following are Jave code examples for showing how to use getTransferData() of the java.awt.datatransfer.Transferable class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-netbeans   File: CustomClientFlavorProvider.java   Source Code and License Vote up 6 votes
public Transferable addDataFlavors(Transferable transferable) {
    try {
        if (transferable.isDataFlavorSupported(ConsumerFlavorProvider.CUSTOM_METHOD_FLAVOR)) {
            Object data = transferable.getTransferData(ConsumerFlavorProvider.CUSTOM_METHOD_FLAVOR);
            if (data instanceof CustomSaasMethod) {
                CustomSaasMethod method = (CustomSaasMethod) data;
                ExTransferable t = ExTransferable.create(transferable);
                CustomClientEditorDrop editorDrop = new CustomClientEditorDrop(method);
                ActiveEditorDropTransferable s = new ActiveEditorDropTransferable(editorDrop);
                t.put(s);
                return t;
            }
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }

    return transferable;
}
 
Example 2
Project: incubator-netbeans   File: ItemTest.java   Source Code and License Vote up 6 votes
/**
 * 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 3
Project: Backmemed   File: GuiScreen.java   Source Code and License Vote up 6 votes
/**
 * Returns a string stored in the system clipboard.
 */
public static String getClipboardString()
{
    try
    {
        Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents((Object)null);

        if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
        {
            return (String)transferable.getTransferData(DataFlavor.stringFlavor);
        }
    }
    catch (Exception var1)
    {
        ;
    }

    return "";
}
 
Example 4
Project: incubator-netbeans   File: DnDSupport.java   Source Code and License Vote up 6 votes
/**
 * Remove a toolbar button represented by the given Transferable.
 */
private void removeButton( Transferable t ) {
    try {
        Object o = null;
        if( t.isDataFlavorSupported(buttonDataFlavor) ) {
            o = t.getTransferData(buttonDataFlavor);
        }
        if( null != o && o instanceof DataObject ) {
            ((DataObject) o).delete();
            sourceToolbar.repaint();
        }
    } catch( UnsupportedFlavorException e ) {
        log.log( Level.INFO, null, e );
    } catch( IOException ioE ) {
        log.log( Level.INFO, null, ioE );
    }
}
 
Example 5
Project: incubator-netbeans   File: DnDSupport.java   Source Code and License Vote up 6 votes
private boolean handleDropImpl(Transferable t) {       
    try {
        Object o;
        if( t.isDataFlavorSupported( actionDataFlavor ) ) {
            o = t.getTransferData( actionDataFlavor );
            if( o instanceof Node ) {
                DataObject dobj = ((Node)o).getLookup().lookup( DataObject.class );
                return addButton( dobj, dropTargetButtonIndex, insertBefore );
            }
        } else {
            o = t.getTransferData( buttonDataFlavor );
            if( o instanceof DataObject ) {
                return moveButton( (DataObject)o, dropTargetButtonIndex, insertBefore );
            }
        }
    } catch( UnsupportedFlavorException e ) {
        log.log( Level.INFO, null, e );
    } catch( IOException ioE ) {
        log.log( Level.INFO, null, ioE );
    }
    return false;
}
 
Example 6
Project: brModelo   File: Diagrama.java   Source Code and License Vote up 6 votes
/**
 * Get the String residing on the clipboard.
 *
 * @return any text found on the Clipboard; if none found, return an empty String. Código copiado da internet.
 */
public static 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 | IOException ex) {
            util.BrLogger.Logger("ERROR_DIAGRAMA_CLIPBOARD", ex.getMessage());
        }
    }
    return result;
}
 
Example 7
Project: rapidminer   File: DataTableColumnDropTextFieldTransferHandler.java   Source Code and License Vote up 6 votes
@Override
public boolean importData(TransferSupport support) {
	if (!canImport(support)) {
		return false;
	}

	try {
		if (currentValueSource != null) {

			// fetch data table column
			Transferable transferable = support.getTransferable();
			DataTableColumnCollection dataTableColumnCollection = (DataTableColumnCollection) transferable
					.getTransferData(DataTableColumnCollection.DATATABLE_COLUMN_COLLECTION_FLAVOR);

			currentValueSource.setDataTableColumn(seriesUsageType, dataTableColumnCollection.getDataTableColumns()
					.get(0));

		}
	} catch (Exception e) {
		e.printStackTrace();
	}

	return false;
}
 
Example 8
Project: Yass   File: YassStringTransferHandler.java   Source Code and License Vote up 5 votes
/**
 * Description of the Method
 *
 * @param c Description of the Parameter
 * @param t Description of the Parameter
 * @return Description of the Return Value
 */
public boolean importData(JComponent c, Transferable t) {
    if (canImport(c, t.getTransferDataFlavors())) {
        try {
            String str = (String) t.getTransferData(DataFlavor.stringFlavor);
            importString(c, str);
            return true;
        } catch (UnsupportedFlavorException | IOException ignored) {
        }
    }

    return false;
}
 
Example 9
Project: imagingbook-common   File: Clipboard.java   Source Code and License Vote up 5 votes
public static String getStringFromClipboard() { 
	String text = null;
	Transferable trf = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); 
	if (trf != null && trf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
		try {
			text = (String) trf.getTransferData(DataFlavor.stringFlavor);
		}  catch (Exception e) {};
	}
	return text; 
}
 
Example 10
Project: logviewer   File: DnDHandler.java   Source Code and License Vote up 5 votes
@Override
public void drop(DnDEvent event) {
    event.setDropPossible(true);
    try {
        DnDNativeTarget.EventInfo eventInfo = (DnDNativeTarget.EventInfo) event.getTransferData(DataFlavor.javaFileListFlavor);
        Transferable transferable = eventInfo.getTransferable();
        List data = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
        for (Object aData : data) {
            dnDListener.onFileDropped((File) aData);
            break;
        }
    } catch (Exception ignored) {
    }
}
 
Example 11
Project: Yass   File: YassMIDIConverter.java   Source Code and License Vote up 5 votes
/**
 * Description of the Method
 *
 * @param dropTargetDropEvent Description of the Parameter
 */
public synchronized void drop(DropTargetDropEvent dropTargetDropEvent) {
    try {
        Transferable tr = dropTargetDropEvent.getTransferable();
        if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            dropTargetDropEvent
                    .acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

            java.util.List fileList = (java.util.List) tr
                    .getTransferData(DataFlavor.javaFileListFlavor);
            Iterator<?> iterator = fileList.iterator();
            while (iterator.hasNext()) {
                File file = (File) iterator.next();
                String fn = file.getAbsolutePath();

                if (fn.endsWith(".kar") || fn.endsWith(".mid")) {
                    filename = fn;
                    if (sequencer.isOpen()) {
                        sequencer.close();
                    }
                    init();
                    openGUI();
                    dropTargetDropEvent.getDropTargetContext()
                            .dropComplete(true);
                    return;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    dropTargetDropEvent.dropComplete(true);
}
 
Example 12
Project: marathonv5   File: ListTransferHandler.java   Source Code and License Vote up 5 votes
@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 13
Project: DIA-Umpire-Maven   File: ClipboardHandlerAWT.java   Source Code and License Vote up 5 votes
/**
 * Gets the contents of the system clipboard
 *
 * @return The text contents of the system clipboard
 */
public String getContents() {
    String contents = null;
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable data = c.getContents(null);
    if (data != null && data.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
            contents = ((String) (data.getTransferData(DataFlavor.stringFlavor)));
        } catch (Exception e) {
            logger.log(Level.WARNING, "Failed getting tranfer data: " + e.getMessage(), e);
        }
    }
    return contents;
}
 
Example 14
Project: jdk8u-jdk   File: WDataTransferer.java   Source Code and License Vote up 4 votes
@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 15
Project: openjdk-jdk10   File: WDataTransferer.java   Source Code and License Vote up 4 votes
@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 = Charset.defaultCharset().name();
        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 16
Project: OpenJSharp   File: WDataTransferer.java   Source Code and License Vote up 4 votes
@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 17
Project: FreeCol   File: DefaultTransferHandler.java   Source Code and License Vote up 4 votes
/**
 * {@inheritDoc}
 */
@Override
public boolean importData(JComponent comp, Transferable t) {
    if (!t.isDataFlavorSupported(DefaultTransferHandler.flavor)) {
        return importFail(comp, "data flavor");
    }

    boolean ret;
    // This variable is used to temporarily keep the old
    // selected unit, while moving cargo from one carrier to another:
    UnitLabel oldSelectedUnit = null;
    try {
        // Get the data to transfer.
        JLabel data = (JLabel)t.getTransferData(DefaultTransferHandler.flavor);
        // Do not allow a transferable to be dropped upon itself:
        if (comp == data) return false;

        // Make sure we don't drop onto other Labels.
        if (comp instanceof AbstractGoodsLabel) {
            comp = getDropTarget(comp);
        } else if (comp instanceof UnitLabel) {
            UnitLabel unitLabel = (UnitLabel)comp;
            /**
             * If the unit/cargo is dropped on a carrier in port
             * then the ship is selected and the unit is added to
             * its cargo.  If the unit is not a carrier, but can
             * be equipped, and the goods can be converted to
             * equipment, equip the unit.
             *
             * If not, assume that the user wished to drop the
             * unit/cargo on the panel below.
             */
            if (unitLabel.getUnit().isCarrier()
                && unitLabel.getParent() instanceof InPortPanel
                && parentPanel instanceof PortPanel) {
                PortPanel portPanel = (PortPanel) parentPanel;
                if (data instanceof Draggable
                    && ((Draggable)data).isOnCarrier()) {
                    oldSelectedUnit = portPanel.getSelectedUnitLabel();
                }
                portPanel.setSelectedUnitLabel(unitLabel);
                comp = portPanel.getCargoPanel();
            } else if (unitLabel.canUnitBeEquippedWith(data)) {
                // don't do anything before partial amount has been checked
            } else {
                comp = getDropTarget(comp);
            }
        }

        ret = (data.getParent() == comp)
            ? importFail(comp, "data-already-present")
            : (data instanceof GoodsLabel)
            ? importGoods(comp, (GoodsLabel)data, oldSelectedUnit)
            : (data instanceof MarketLabel)
            ? importMarket(comp, (MarketLabel)data)
            : (data instanceof UnitLabel)
            ? importUnit(comp, (UnitLabel)data, oldSelectedUnit)
            : importFail(comp, data.toString());
    } catch (Exception e) { // FIXME: Suggest a reconnect?
        logger.log(Level.WARNING, "Import fail", e);
        ret = importFail(comp, "crash: " + e.toString());
    }
    return ret;
}
 
Example 18
Project: TrabalhoFinalEDA2   File: mxGraphTransferHandler.java   Source Code and License Vote up 4 votes
/**
 * Checks if the mxGraphTransferable data flavour is supported and calls
 * importGraphTransferable if possible.
 */
public boolean importData(JComponent c, Transferable t)
{
	boolean result = false;

	if (isLocalDrag())
	{
		// Enables visual feedback on the Mac
		result = true;
	}
	else
	{
		try
		{
			updateImportCount(t);

			if (c instanceof mxGraphComponent)
			{
				mxGraphComponent graphComponent = (mxGraphComponent) c;

				if (graphComponent.isEnabled()
						&& t.isDataFlavorSupported(mxGraphTransferable.dataFlavor))
				{
					mxGraphTransferable gt = (mxGraphTransferable) t
							.getTransferData(mxGraphTransferable.dataFlavor);

					if (gt.getCells() != null)
					{
						result = importGraphTransferable(graphComponent, gt);
					}

				}
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	return result;
}
 
Example 19
Project: freecol   File: DefaultTransferHandler.java   Source Code and License Vote up 4 votes
/**
 * {@inheritDoc}
 */
@Override
public boolean importData(JComponent comp, Transferable t) {
    if (!t.isDataFlavorSupported(DefaultTransferHandler.flavor)) {
        return importFail(comp, "data flavor");
    }

    boolean ret;
    // This variable is used to temporarily keep the old
    // selected unit, while moving cargo from one carrier to another:
    UnitLabel oldSelectedUnit = null;
    try {
        // Get the data to transfer.
        JLabel data = (JLabel)t.getTransferData(DefaultTransferHandler.flavor);
        // Do not allow a transferable to be dropped upon itself:
        if (comp == data) return false;

        // Make sure we don't drop onto other Labels.
        if (comp instanceof AbstractGoodsLabel) {
            comp = getDropTarget(comp);
        } else if (comp instanceof UnitLabel) {
            UnitLabel unitLabel = (UnitLabel)comp;
            /**
             * If the unit/cargo is dropped on a carrier in port
             * then the ship is selected and the unit is added to
             * its cargo.  If the unit is not a carrier, but can
             * be equipped, and the goods can be converted to
             * equipment, equip the unit.
             *
             * If not, assume that the user wished to drop the
             * unit/cargo on the panel below.
             */
            if (unitLabel.getUnit().isCarrier()
                && unitLabel.getParent() instanceof InPortPanel
                && parentPanel instanceof PortPanel) {
                PortPanel portPanel = (PortPanel) parentPanel;
                if (data instanceof Draggable
                    && ((Draggable)data).isOnCarrier()) {
                    oldSelectedUnit = portPanel.getSelectedUnitLabel();
                }
                portPanel.setSelectedUnitLabel(unitLabel);
                comp = portPanel.getCargoPanel();
            } else if (unitLabel.canUnitBeEquippedWith(data)) {
                // don't do anything before partial amount has been checked
            } else {
                comp = getDropTarget(comp);
            }
        }

        ret = (data.getParent() == comp)
            ? importFail(comp, "data-already-present")
            : (data instanceof GoodsLabel)
            ? importGoods(comp, (GoodsLabel)data, oldSelectedUnit)
            : (data instanceof MarketLabel)
            ? importMarket(comp, (MarketLabel)data)
            : (data instanceof UnitLabel)
            ? importUnit(comp, (UnitLabel)data, oldSelectedUnit)
            : importFail(comp, data.toString());
    } catch (Exception e) { // FIXME: Suggest a reconnect?
        logger.log(Level.WARNING, "Import fail", e);
        ret = importFail(comp, "crash: " + e.toString());
    }
    return ret;
}
 
Example 20
Project: jdk8u-jdk   File: SunClipboard.java   Source Code and License Vote up 4 votes
/**
 * @see java.awt.Clipboard#getData
 * @since 1.5
 */
public Object getData(DataFlavor flavor)
    throws UnsupportedFlavorException, IOException {
    if (flavor == null) {
        throw new NullPointerException("flavor");
    }

    Transferable cntnts = getContextContents();
    if (cntnts != null) {
        return cntnts.getTransferData(flavor);
    }

    long format = 0;
    byte[] data = null;
    Transferable localeTransferable = null;

    try {
        openClipboard(null);

        long[] formats = getClipboardFormats();
        Long lFormat = (Long)DataTransferer.getInstance().
                getFlavorsForFormats(formats, getDefaultFlavorTable()).get(flavor);

        if (lFormat == null) {
            throw new UnsupportedFlavorException(flavor);
        }

        format = lFormat.longValue();
        data = getClipboardData(format);

        if (DataTransferer.getInstance().isLocaleDependentTextFormat(format)) {
            localeTransferable = createLocaleTransferable(formats);
        }

    } finally {
        closeClipboard();
    }

    return DataTransferer.getInstance().
            translateBytes(data, flavor, format, localeTransferable);
}