List of usage examples for java.awt.datatransfer Transferable getTransferDataFlavors
public DataFlavor[] getTransferDataFlavors();
From source file:DragFileDemo.java
public boolean importData(JComponent c, Transferable t) { JTextArea tc;//from w w w .j av a 2s.c o m if (!canImport(c, t.getTransferDataFlavors())) { return false; } //A real application would load the file in another //thread in order to not block the UI. This step //was omitted here to simplify the code. try { if (hasFileFlavor(t.getTransferDataFlavors())) { String str = null; java.util.List files = (java.util.List) t.getTransferData(fileFlavor); for (int i = 0; i < files.size(); i++) { File file = (File) files.get(i); //Tell the tabbedpane controller to add //a new tab with the name of this file //on the tab. The text area that will //display the contents of the file is returned. tc = tpc.addTab(file.toString()); BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); while ((str = in.readLine()) != null) { tc.append(str + newline); } } catch (IOException ioe) { System.out.println("importData: Unable to read from file " + file.toString()); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { System.out.println("importData: Unable to close file " + file.toString()); } } } } return true; } else if (hasStringFlavor(t.getTransferDataFlavors())) { tc = (JTextArea) c; if (tc.equals(source) && (tc.getCaretPosition() >= p0.getOffset()) && (tc.getCaretPosition() <= p1.getOffset())) { shouldRemove = false; return true; } String str = (String) t.getTransferData(stringFlavor); tc.replaceSelection(str); return true; } } catch (UnsupportedFlavorException ufe) { System.out.println("importData: unsupported data flavor"); } catch (IOException ieo) { System.out.println("importData: I/O exception"); } return false; }
From source file:com.projity.pm.graphic.spreadsheet.common.transfer.NodeListTransferHandler.java
public boolean importData(JComponent c, Transferable t) { SpreadSheet spreadSheet = getSpreadSheet(c); if (spreadSheet == null) return false; DataFlavor flavor = getFlavor(t.getTransferDataFlavors()); if (flavor != null) { try {//ww w.ja v a 2 s . c o m NodeModel model = ((CommonSpreadSheetModel) spreadSheet.getModel()).getCache().getModel(); Object data = t.getTransferData(flavor); if (data == null) return false; List nodes = null; if (data instanceof ArrayList) { nodes = (List) data; for (Iterator i = nodes.iterator(); i.hasNext();) { Node node = (Node) i.next(); transformSubprojectBranches(node, model.getDataFactory(), new Predicate() { public boolean evaluate(Object arg0) { Node parent = (Node) arg0; //change implementation NormalTask task = new NormalTask(); Task source = ((Task) parent.getImpl()); source.cloneTo(task); //task.setDuration(source.getActualDuration()); parent.setImpl(task); return true; } }); } SpreadSheet.SpreadSheetAction a = getNodeListPasteAction().getSpreadSheetAction(); a.execute(nodes); } else if (data instanceof String) { // ArrayList fields=spreadSheet.getSelectedFields(); // if (fields==null){ // fields=spreadSheet.getSelectableFields(); //The whole line is selected // nodes=NodeListTransferable.stringToNodeList((String)data,spreadSheet,fields,model.getDataFactory()); // }else{ // NodeListTransferable.pasteString((String)data,spreadSheet); // } NodeListTransferable.pasteString((String) data, spreadSheet); } else return false; return true; } catch (UnsupportedFlavorException ufe) { } catch (IOException ioe) { } } return false; }
From source file:DragPictureDemo2.java
public boolean importData(JComponent c, Transferable t) { Image image;/*w w w . jav a 2 s. c o m*/ if (canImport(c, t.getTransferDataFlavors())) { DTPicture pic = (DTPicture) c; //Don't drop on myself. if (sourcePic == pic) { shouldRemove = false; return true; } try { image = (Image) t.getTransferData(pictureFlavor); //Set the component to the new picture. pic.setImage(image); return true; } catch (UnsupportedFlavorException ufe) { System.out.println("importData: unsupported data flavor"); } catch (IOException ioe) { System.out.println("importData: I/O exception"); } } return false; }
From source file:com.frostwire.gui.library.LibraryFilesTransferHandler.java
@Override public boolean importData(TransferSupport support) { if (!canImport(support)) { return false; }// w w w .ja va2 s. c o m try { Transferable transferable = support.getTransferable(); LibraryNode node = getNodeFromLocation(support.getDropLocation()); if (node instanceof DeviceNode || node instanceof DeviceFileTypeTreeNode) { File[] files = null; if (DNDUtils.contains(transferable.getTransferDataFlavors(), LibraryPlaylistsTableTransferable.ITEM_ARRAY)) { PlaylistItem[] playlistItems = LibraryUtils .convertToPlaylistItems((LibraryPlaylistsTableTransferable.Item[]) transferable .getTransferData(LibraryPlaylistsTableTransferable.ITEM_ARRAY)); files = LibraryUtils.convertToFiles(playlistItems); } else { files = DNDUtils.getFiles(support.getTransferable()); } if (files != null) { Device device = null; if (node instanceof DeviceNode) { device = ((DeviceNode) node).getDevice(); } else if (node instanceof DeviceFileTypeTreeNode) { device = ((DeviceFileTypeTreeNode) node).getDevice(); } if (device != null) { device.upload(files); } } } else { if (node instanceof DirectoryHolderNode) { DirectoryHolder dirHolder = ((DirectoryHolderNode) node).getDirectoryHolder(); if (droppingFoldersToAddToLibrary(support, dirHolder, false)) { try { //add to library File[] files = DNDUtils.getFiles(support.getTransferable()); for (File f : files) { LibrarySettings.DIRECTORIES_TO_INCLUDE.add(f); LibrarySettings.DIRECTORIES_NOT_TO_INCLUDE.remove(f); } LibraryMediator.instance().clearDirectoryHolderCaches(); //show tools -> library option pane GUIMediator.instance().setOptionsVisible(true, OptionsConstructor.LIBRARY_KEY); } catch (Exception e) { e.printStackTrace(); } } } else if (DNDUtils.contains(transferable.getTransferDataFlavors(), LibraryPlaylistsTableTransferable.ITEM_ARRAY)) { PlaylistItem[] playlistItems = LibraryUtils .convertToPlaylistItems((LibraryPlaylistsTableTransferable.Item[]) transferable .getTransferData(LibraryPlaylistsTableTransferable.ITEM_ARRAY)); LibraryUtils.createNewPlaylist(playlistItems, isStarredDirectoryHolder(support.getDropLocation())); } else { File[] files = DNDUtils.getFiles(support.getTransferable()); if (files.length == 1 && files[0].getAbsolutePath().endsWith(".m3u")) { LibraryUtils.createNewPlaylist(files[0], isStarredDirectoryHolder(support.getDropLocation())); } else { LibraryUtils.createNewPlaylist(files, isStarredDirectoryHolder(support.getDropLocation())); } } } } catch (Throwable e) { LOG.error("Error in LibraryFilesTransferHandler processing", e); } return false; }
From source file:net.sf.nmedit.jtheme.component.JTModuleContainer.java
public void dropPatchFile(DropTargetDropEvent dtde) { Transferable transfer = dtde.getTransferable(); PPatch patch = getModuleContainer().getPatch(); DataFlavor fileFlavor = FileDnd.getFileFlavor(transfer.getTransferDataFlavors()); List<File> files = FileDnd.getTransferableFiles(fileFlavor, transfer); if (files.size() == 1) { PPatch newPatch;//from w w w. j a va2 s. com try { newPatch = patch.createFromFile(files.get(0)); } catch (Exception e) { newPatch = null; } if (newPatch != null) { if (dropPatch(newPatch, dtde.getLocation())) { dtde.dropComplete(true); } else { dtde.rejectDrop(); dtde.dropComplete(false); } } else { dtde.rejectDrop(); dtde.dropComplete(false); } } else { dtde.rejectDrop(); dtde.dropComplete(false); } }
From source file:net.sf.nmedit.nomad.core.Nomad.java
public void export() { Document doc = getDocumentManager().getSelection(); if (!(doc instanceof Transferable)) return;//from w w w . j a v a 2s. c o m Transferable transferable = (Transferable) doc; String title = doc.getTitle(); if (title == null) title = "Export"; else title = "Export '" + title + "'"; JComboBox src = new JComboBox(transferable.getTransferDataFlavors()); src.setRenderer(new DefaultListCellRenderer() { /** * */ private static final long serialVersionUID = -4553255745845039428L; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String text; if (value instanceof DataFlavor) { DataFlavor flavor = (DataFlavor) value; String mimeType = flavor.getMimeType(); String humanRep = flavor.getHumanPresentableName(); String charset = flavor.getParameter("charset"); if (mimeType == null) text = "?"; else { text = mimeType; int ix = text.indexOf(';'); if (ix >= 0) text = text.substring(0, ix).trim(); } if (charset != null) text += "; charset=" + charset; if (humanRep != null) text += " (" + humanRep + ")"; } else { text = String.valueOf(value); } return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus); } }); JComboBox dst = new JComboBox(new Object[] { "File", "Clipboard" }); Object[] msg = { "Source:", doc.getTitle(), "Export as:", src, "Export to:", dst }; Object[] options = { "Ok", "Cancel" }; JOptionPane op = new JOptionPane(msg, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options); JDialog dialog = op.createDialog(getWindow(), title); dialog.setModal(true); dialog.setVisible(true); boolean ok = "Ok".equals(op.getValue()); DataFlavor flavor = (DataFlavor) src.getSelectedItem(); dialog.dispose(); if (!ok) return; if (flavor == null) return; if ("Clipboard".equals(dst.getSelectedItem())) { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); cb.setContents(new SelectedTransfer(flavor, transferable), null); } else { export(transferable, flavor); } }
From source file:net.sf.jabref.groups.EntryTableTransferHandler.java
/** * This method is called when stuff is drag to the component. * * Imports the dropped URL or plain text as a new entry in the current database. * *///from w w w. java2 s. c o m @Override public boolean importData(JComponent comp, Transferable t) { // If the drop target is the main table, we want to record which // row the item was dropped on, to identify the entry if needed: int dropRow = -1; if (comp instanceof JTable) { dropRow = ((JTable) comp).getSelectedRow(); } try { // This flavor is used for dragged file links in Windows: if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { // JOptionPane.showMessageDialog(null, "Received // javaFileListFlavor"); List<File> l = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor); return handleDraggedFiles(l, dropRow); } else if (t.isDataFlavorSupported(urlFlavor)) { URL dropLink = (URL) t.getTransferData(urlFlavor); return handleDropTransfer(dropLink); } else if (t.isDataFlavorSupported(stringFlavor)) { String dropStr = (String) t.getTransferData(stringFlavor); LOGGER.debug("Received stringFlavor: " + dropStr); return handleDropTransfer(dropStr, dropRow); } } catch (IOException ioe) { LOGGER.error("Failed to read dropped data", ioe); } catch (UnsupportedFlavorException ufe) { LOGGER.error("Drop type error", ufe); } // all supported flavors failed LOGGER.info("Can't transfer input: "); DataFlavor[] inflavs = t.getTransferDataFlavors(); for (DataFlavor inflav : inflavs) { LOGGER.info(" " + inflav); } return false; }
From source file:net.sf.jabref.gui.groups.EntryTableTransferHandler.java
/** * This method is called when stuff is drag to the component. * * Imports the dropped URL or plain text as a new entry in the current database. * *///w w w .ja v a2 s .c om @Override public boolean importData(JComponent comp, Transferable t) { // If the drop target is the main table, we want to record which // row the item was dropped on, to identify the entry if needed: int dropRow = -1; if (comp instanceof JTable) { dropRow = ((JTable) comp).getSelectedRow(); } try { // This flavor is used for dragged file links in Windows: if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { // JOptionPane.showMessageDialog(null, "Received // javaFileListFlavor"); List<File> l = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor); return handleDraggedFiles(l, dropRow); } else if (t.isDataFlavorSupported(urlFlavor)) { URL dropLink = (URL) t.getTransferData(urlFlavor); return handleDropTransfer(dropLink); } else if (t.isDataFlavorSupported(stringFlavor)) { String dropStr = (String) t.getTransferData(stringFlavor); LOGGER.debug("Received stringFlavor: " + dropStr); return handleDropTransfer(dropStr, dropRow); } } catch (IOException ioe) { LOGGER.error("Failed to read dropped data", ioe); } catch (UnsupportedFlavorException | ClassCastException ufe) { LOGGER.error("Drop type error", ufe); } // all supported flavors failed LOGGER.info("Can't transfer input: "); DataFlavor[] inflavs = t.getTransferDataFlavors(); for (DataFlavor inflav : inflavs) { LOGGER.info(" " + inflav); } return false; }
From source file:net.sf.jabref.gui.fieldeditors.FileListEditorTransferHandler.java
@Override public boolean importData(JComponent comp, Transferable t) { // If the drop target is the main table, we want to record which // row the item was dropped on, to identify the entry if needed: try {//from ww w.j a v a2 s. c o m List<File> files = new ArrayList<>(); // This flavor is used for dragged file links in Windows: if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { files.addAll((List<File>) t.getTransferData(DataFlavor.javaFileListFlavor)); } if (t.isDataFlavorSupported(urlFlavor)) { URL dropLink = (URL) t.getTransferData(urlFlavor); LOGGER.debug("URL: " + dropLink); } // This is used when one or more files are pasted from the file manager // under Gnome. The data consists of the file paths, one file per line: if (t.isDataFlavorSupported(stringFlavor)) { String dropStr = (String) t.getTransferData(stringFlavor); files.addAll(EntryTableTransferHandler.getFilesFromDraggedFilesString(dropStr)); } SwingUtilities.invokeLater(() -> { for (File file : files) { // Find the file's extension, if any: String name = file.getAbsolutePath(); FileUtil.getFileExtension(name).ifPresent(extension -> ExternalFileTypes.getInstance() .getExternalFileTypeByExt(extension).ifPresent(fileType -> { if (droppedFileHandler == null) { droppedFileHandler = new DroppedFileHandler(frame, frame.getCurrentBasePanel()); } droppedFileHandler.handleDroppedfile(name, fileType, entryContainer.getEntry()); })); } }); if (!files.isEmpty()) { // Found some files, return return true; } } catch (IOException ioe) { LOGGER.warn("Failed to read dropped data. ", ioe); } catch (UnsupportedFlavorException | ClassCastException ufe) { LOGGER.warn("Drop type error. ", ufe); } // all supported flavors failed StringBuilder logMessage = new StringBuilder("Cannot transfer input:"); DataFlavor[] inflavs = t.getTransferDataFlavors(); for (DataFlavor inflav : inflavs) { logMessage.append(' ').append(inflav); } LOGGER.warn(logMessage.toString()); return false; }
From source file:org.apache.jmeter.gui.MainFrame.java
/** * Handler of Top level Dnd//from w ww. j a v a 2s .co m */ @Override public void drop(DropTargetDropEvent dtde) { try { Transferable tr = dtde.getTransferable(); DataFlavor[] flavors = tr.getTransferDataFlavors(); for (DataFlavor flavor : flavors) { // Check for file lists specifically if (flavor.isFlavorJavaFileListType()) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); try { openJmxFilesFromDragAndDrop(tr); } finally { dtde.dropComplete(true); } return; } } } catch (UnsupportedFlavorException | IOException e) { log.warn("Dnd failed", e); } }