List of usage examples for java.awt.datatransfer Transferable getTransferData
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException;
From source file:DragFileDemo.java
public boolean importData(JComponent c, Transferable t) { JTextArea tc;/*from w w w. j a v a2 s . 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.frostwire.gui.library.LibraryFilesTransferHandler.java
@Override public boolean importData(TransferSupport support) { if (!canImport(support)) { return false; }// www .ja v a2 s.co 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:com.kstenschke.copypastestack.ToolWindow.java
/** * Refresh listed items from distinct merged sum of: * 0. option to preview the current clipboard contents * 1. previous clipboard items still in prefs * 2. current clipboard items/*from w ww . ja v a 2 s . c o m*/ */ private void refreshClipboardList() { Transferable[] copiedItems = CopyPasteManager.getInstance().getAllContents(); int amountItems = UtilsClipboard.getAmountStringItemsInTransferables(copiedItems); String[] itemsUnique = null; boolean hasClipboardContent = UtilsClipboard.hasContent(); String[] copyItemsList = new String[amountItems]; if (amountItems > 0 || hasClipboardContent) { // Add copied string items, historic and current int index = 0; for (Transferable currentItem : copiedItems) { if (currentItem.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String itemStr = currentItem.getTransferData(DataFlavor.stringFlavor).toString(); if (!itemStr.trim().isEmpty()) { copyItemsList[index] = itemStr; index++; } } catch (Exception e) { e.printStackTrace(); } } } // Tidy items: distinct items, none empty String[] copyItemsPref = Preferences.getItems(); Object[] allItems = (copyItemsPref.length > 0) ? ArrayUtils.addAll(copyItemsList, copyItemsPref) : copyItemsList; itemsUnique = UtilsArray.tidy(allItems); if (itemsUnique.length > 0) { this.setClipboardListData(itemsUnique, false); this.sortClipboardListByTags(this.form.checkboxKeepSorted.isSelected()); Preferences.saveCopyItems(itemsUnique); } } initStatusLabel(itemsUnique == null ? 0 : itemsUnique.length); }
From source file:ScribbleDragAndDrop.java
/** * This is the key method of DropTargetListener. It is invoked when the user * drops something on us./*from w ww. j a v a2 s . c om*/ */ public void drop(DropTargetDropEvent e) { this.setBorder(normalBorder); // Restore the default border // First, check whether we understand the data that was dropped. // If we supports our data flavors, accept the drop, otherwise reject. if (e.isDataFlavorSupported(Scribble.scribbleDataFlavor) || e.isDataFlavorSupported(DataFlavor.stringFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); } else { e.rejectDrop(); return; } // We've accepted the drop, so now we attempt to get the dropped data // from the Transferable object. Transferable t = e.getTransferable(); // Holds the dropped data Scribble droppedScribble; // This will hold the Scribble object // First, try to get the data directly as a scribble object try { droppedScribble = (Scribble) t.getTransferData(Scribble.scribbleDataFlavor); } catch (Exception ex) { // unsupported flavor, IO exception, etc. // If that doesn't work, try to get it as a String and parse it try { String s = (String) t.getTransferData(DataFlavor.stringFlavor); droppedScribble = Scribble.parse(s); } catch (Exception ex2) { // If we still couldn't get the data, tell the system we failed e.dropComplete(false); return; } } // If we get here, we've got the Scribble object Point p = e.getLocation(); // Where did the drop happen? droppedScribble.translate(p.getX(), p.getY()); // Move it there scribbles.add(droppedScribble); // add to display list repaint(); // ask for redraw e.dropComplete(true); // signal success! }
From source file:de.tor.tribes.ui.views.DSWorkbenchTagFrame.java
private void pasteVillagesFromClipboard() { List<Village> villages = null; try {// w ww . j a v a 2 s . com Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); villages = PluginManager.getSingleton() .executeVillageParser((String) t.getTransferData(DataFlavor.stringFlavor)); if (villages == null || villages.isEmpty()) { showInfo("Keine Drfer in der Zwischenablage gefunden"); return; } } catch (Exception e) { logger.error("Failed to read data from clipboard", e); showError("Fehler beim Lesen aus der Zwischenablage"); } fireVillagesDraggedEvent(villages, null); }
From source file:net.sf.nmedit.jtheme.component.JTModuleContainer.java
public void copyMoveModules(DropTargetDropEvent dtde) { DataFlavor chosen = PDragDrop.ModuleSelectionFlavor; Transferable transfer = dtde.getTransferable(); Object data = null;/* w ww.j a v a 2s . co m*/ try { // Get the data data = transfer.getTransferData(chosen); dtde.acceptDrop(dtde.getDropAction() & (DnDConstants.ACTION_MOVE | DnDConstants.ACTION_COPY | DnDConstants.ACTION_LINK)); } catch (Throwable t) { if (log.isWarnEnabled()) { log.warn("copyMoveModules(DropTargetDropEvent=" + dtde + ") failed", t); } dtde.dropComplete(false); return; } if (data != null && data instanceof PModuleTransferData) { // Cast the data and create a nice module. PModuleTransferData tdata = ((PModuleTransferData) data); boolean isSamePatch = false; if (tdata.getSourcePatch() == getModuleContainer().getPatch()) isSamePatch = true; //Point p = dtde.getLocation(); int action = dtde.getDropAction(); if ((action & DnDConstants.ACTION_MOVE) != 0 && isSamePatch) { MoveOperation op = tdata.getSourceModuleContainer().createMoveOperation(); op.setDestination(getModuleContainer()); executeOperationOnSelection(tdata, dtde.getLocation(), op); } else { copyModules(tdata, dtde.getLocation(), ((dtde.getDropAction() & DnDConstants.ACTION_LINK) != 0)); } } dtde.dropComplete(true); }
From source file:gdt.jgui.entity.folder.JFolderPanel.java
private boolean hasToInsert() { try {//from w w w . ja v a 2 s. c om Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable clipboardContents = systemClipboard.getContents(null); if (clipboardContents == null) return false; Object transferData = clipboardContents.getTransferData(DataFlavor.javaFileListFlavor); @SuppressWarnings("unchecked") List<File> files = (List<File>) transferData; for (int i = 0; i < files.size(); i++) { File file = (File) files.get(i); if (file.exists() && file.isFile()) return true; } } catch (Exception ee) { LOGGER.severe(ee.toString()); } return false; }
From source file:net.technicpack.launcher.ui.LauncherFrame.java
protected void pasteUpdated(Transferable transferable) { String text;//from w w w . j a va2 s . co m if (!transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) return; try { text = transferable.getTransferData(DataFlavor.stringFlavor).toString(); } catch (IOException ex) { Utils.getLogger().log(Level.SEVERE, ex.getMessage(), ex); return; } catch (UnsupportedFlavorException ex) { Utils.getLogger().log(Level.SEVERE, ex.getMessage(), ex); return; } try { final URL platformUrl = new URL(text); new SwingWorker<PlatformPackInfo, Void>() { @Override protected PlatformPackInfo doInBackground() throws Exception { PlatformPackInfo info = RestObject.getRestObject(PlatformPackInfo.class, platformUrl.toString()); //Don't let people jerk us around with non-platform sites- make sure this is a real pack //on the technic platform return platformApi.getPlatformPackInfo(info.getName()); } @Override public void done() { PlatformPackInfo result; try { result = get(); if (result == null) return; } catch (ExecutionException ex) { //We eat these two exceptions because they are almost certainly caused by //the pasted text not being relevant to this program return; } catch (InterruptedException ex) { return; } if (!packRepo.getInstalledPacks().containsKey(result.getName())) { packRepo.put(new InstalledPack(result.getName(), true, InstalledPack.RECOMMENDED)); } packRepo.setSelectedSlug(result.getName()); modpackSelector.forceRefresh(); LauncherFrame.this.setExtendedState(JFrame.ICONIFIED); EventQueue.invokeLater(new Runnable() { @Override public void run() { LauncherFrame.this.setExtendedState(JFrame.NORMAL); EventQueue.invokeLater(new Runnable() { @Override public void run() { LauncherFrame.this.selectTab("modpacks"); } }); } }); } }.execute(); } catch (MalformedURLException ex) { return; } }
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. * *///from ww w .j ava 2 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.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. j a va 2s. co 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; }