Java Code Examples for java.awt.datatransfer.Clipboard#getContents()

The following examples show how to use java.awt.datatransfer.Clipboard#getContents() . 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 check out the related API usage on the sidebar.
Example 1
Source File: AbstractDockingTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Gets any current text on the clipboard
 *
 * @return the text on the clipboard; null if no text is on the clipboard
 * @throws Exception if there are any issues copying from the clipboard
 */
public String getClipboardText() throws Exception {
	Clipboard c = GClipboard.getSystemClipboard();
	Transferable t = c.getContents(null);

	try {
		String text = (String) t.getTransferData(DataFlavor.stringFlavor);
		return text;
	}
	catch (UnsupportedFlavorException e) {
		Msg.error(this, "Unsupported data flavor - 'string'.  Supported flavors: ");
		DataFlavor[] flavors = t.getTransferDataFlavors();
		for (DataFlavor dataFlavor : flavors) {
			Msg.error(this, "\t" + dataFlavor.getHumanPresentableName());
		}
		throw e;
	}
}
 
Example 2
Source File: TextClipboardHandler.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String pasteText()
{
	Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	Transferable clipboardContents = systemClipboard.getContents(null);

	if (clipboardContents != null) {
		try {
			if (clipboardContents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
				return (String)clipboardContents.getTransferData(DataFlavor.stringFlavor);
			}
		} catch (UnsupportedFlavorException ufe) {
			ufe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	return null;
}
 
Example 3
Source File: PasteAction.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isEnabledForContext(SymbolTreeActionContext context) {

	TreePath[] selectionPaths = context.getSelectedSymbolTreePaths();
	if (selectionPaths.length != 1) {
		return false;
	}

	Object pathComponent = selectionPaths[0].getLastPathComponent();
	if (!(pathComponent instanceof SymbolTreeNode)) {
		return false;
	}

	SymbolTreeNode node = (SymbolTreeNode) pathComponent;
	Clipboard clipboard = context.getSymbolTreeProvider().getClipboard();
	Transferable transferable = clipboard.getContents(this);
	if (transferable == null) {
		return false;
	}
	return node.supportsDataFlavors(transferable.getTransferDataFlavors());
}
 
Example 4
Source File: ClipboardMenuController.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
private
static
boolean
canPaste()
{
  Clipboard clipboard = getDefaultToolkit().getSystemClipboard();
  Transferable contents = clipboard.getContents(null);
  String data = null;

  if(contents != null)
  {
    if(contents.isDataFlavorSupported(stringFlavor))
    {
      try
      {
        data = (String)contents.getTransferData(stringFlavor);
      }
      catch(Exception exception)
      {
        // Ignored.
      }
    }
  }

  return data != null;
}
 
Example 5
Source File: ClipboardHandler.java    From Spade with GNU General Public License v3.0 6 votes vote down vote up
public static RawImage getImage()
{
	Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
	Transferable transfer = clip.getContents(null);
	if(transfer != null && transfer.isDataFlavorSupported(DataFlavor.imageFlavor))
	{
		try
		{
			Image image = (Image) transfer.getTransferData(DataFlavor.imageFlavor);
			BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
			
			Graphics2D g = bufferedImage.createGraphics();
			g.drawImage(image, 0, 0, null);
			g.dispose();
			
			return RawImage.unwrapBufferedImage(bufferedImage);
		}
		catch(UnsupportedFlavorException | IOException e)
		{
			e.printStackTrace();
		}
	}
	return null;
}
 
Example 6
Source File: LibraryTreePanel.java    From osp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Determines if the clipboard can be pasted.
 * 
 * @return true if the clipboard contains a LibraryTreeNode XMLControl string
 */
protected boolean isClipboardPastable() {
	pasteControl = null;
  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
  Transferable data = clipboard.getContents(null);
  String dataString = null;
try {
	dataString = (String)data.getTransferData(DataFlavor.stringFlavor);
} catch (Exception e) {} 
if(dataString!=null) {
    XMLControlElement control = new XMLControlElement();
    control.readXML(dataString);
    if (LibraryResource.class.isAssignableFrom(control.getObjectClass())) {
    	pasteControl = control;
    	return true;
    }
  }
  return false;
}
 
Example 7
Source File: PasteFromClipboardPlugin.java    From constellation with Apache License 2.0 6 votes vote down vote up
@Override
protected void edit(final GraphWriteMethods wg, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
    try {
        final Clipboard cb = ConstellationClipboardOwner.getConstellationClipboard();
        if (cb.isDataFlavorAvailable(RecordStoreTransferable.RECORDSTORE_FLAVOR)) {
            final RecordStoreTransferable rt = (RecordStoreTransferable) cb.getContents(null);
            final RecordStore cbRecordStore = (RecordStore) rt.getTransferData(RecordStoreTransferable.RECORDSTORE_FLAVOR);
            if (cbRecordStore != null) {
                // There is a graph on the local clipboard.
                PluginExecution.withPlugin(InteractiveGraphPluginRegistry.PASTE_GRAPH)
                        .withParameter(PasteGraphPlugin.RECORDSTORE_PARAMETER_ID, cbRecordStore)
                        .executeNow(wg);
            }
        }
    } catch (UnsupportedFlavorException | IOException ex) {
        Exceptions.printStackTrace(ex);
    }

}
 
Example 8
Source File: ClipboardUtil.java    From pgptool with GNU General Public License v3.0 5 votes vote down vote up
public static String tryGetClipboardText() {
	Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	Transferable contents = clipboard.getContents(null);
	boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor);
	if (!hasTransferableText) {
		return null;
	}

	try {
		return (String) contents.getTransferData(DataFlavor.stringFlavor);
	} catch (UnsupportedFlavorException | IOException ex) {
		log.warn("Can't get clipboard text contents", ex);
		return null;
	}
}
 
Example 9
Source File: PasteFromX11Action.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected Transferable getContentsToPaste(Editor editor, DataContext dataContext) {
  Clipboard clip = editor.getComponent().getToolkit().getSystemSelection();
  if (clip == null) return null;

  try {
    return clip.getContents(null);
  }
  catch (Exception e) {
    LOG.info(e);
    return null;
  }
}
 
Example 10
Source File: TaxaListHasData.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean clipBoardHasString() {

		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable t = clip.getContents(this);
		try {
			String s = (String) t.getTransferData(DataFlavor.stringFlavor);
			if (s != null) {
				return true;
			}
		} catch (Exception e) {
			MesquiteMessage.printStackTrace(e);
		}
		return false;
	}
 
Example 11
Source File: ShellTextComponent.java    From basicv2 with The Unlicense 5 votes vote down vote up
private static String getClipBoardString() throws Exception {
	Clipboard clipboard = getDefaultToolkit().getSystemClipboard();
	Transferable clipData = clipboard.getContents(clipboard);
	if (clipData != null) {
		if (clipData.isDataFlavorSupported(stringFlavor)) {
			return (String) (clipData.getTransferData(stringFlavor));
		}
	}
	throw new Exception("no clpboard data");
}
 
Example 12
Source File: CharacterData.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void pasteDataIntoTaxon(int it) {

		Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable t = clip.getContents(this);
		try {
			String s = (String) t.getTransferData(DataFlavor.stringFlavor);
			pasteDataFromStringIntoTaxon(it, s);
		} catch (Exception e) {
			MesquiteMessage.printStackTrace(e);
		}
	}
 
Example 13
Source File: DataTool.java    From osp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Pastes from the clipboard and returns the pasted string.
 *
 * @return the pasted string, or null if none
 */
public static String paste() {
  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
  Transferable data = clipboard.getContents(null);
  if((data!=null)&&data.isDataFlavorSupported(DataFlavor.stringFlavor)) {
    try {
      String text = (String) data.getTransferData(DataFlavor.stringFlavor);
      return text;
    } catch(Exception ex) {
      ex.printStackTrace();
    }
  }
  return null;
}
 
Example 14
Source File: FunctionEditor.java    From osp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the clipboard contents.
 */
protected XMLControl[] getClipboardContents() {
  try {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable tran = clipboard.getContents(null);
    String dataString = (String) tran.getTransferData(DataFlavor.stringFlavor);
    if(dataString!=null) {
      XMLControlElement control = new XMLControlElement();
      control.readXML(dataString);
      if(control.getObjectClass()==this.getClass()) {
        java.util.List<Object> list = control.getPropertyContent();
        for(int i = 0; i<list.size(); i++) {
          Object next = list.get(i);
          if(next instanceof XMLProperty) {
            XMLProperty prop = (XMLProperty) next;
            if(prop.getPropertyName().equals("selected")) { //$NON-NLS-1$
              return prop.getChildControls();
            }
          }
        }
        return null;
      }
    }
  } catch(Exception ex) {
    /** empty block */
  }
  return null;
}
 
Example 15
Source File: RuntimeLogic.java    From EchoSim with Apache License 2.0 5 votes vote down vote up
public static void pasteSpec(RuntimeBean runtime) throws IOException, URISyntaxException, UnsupportedFlavorException, ParseException
{
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable contents = clipboard.getContents(null);
    if ((contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor))
    {
        String json = (String)contents.getTransferData(DataFlavor.stringFlavor);
        JSONObject jspec = (JSONObject)mParser.parse(json);
        AppSpecBean spec = FromJSONLogic.fromJSONAppSpec(jspec);
        selectMRU(runtime, spec);
    }
}
 
Example 16
Source File: ParticleDataTrack.java    From tracker with GNU General Public License v3.0 5 votes vote down vote up
protected static boolean isImportableClipboard(Clipboard clipboard) {
   Transferable data = clipboard.getContents(null);
   if (data != null && data.isDataFlavorSupported(DataFlavor.stringFlavor)) {
   	try {
			String s = (String)data.getTransferData(DataFlavor.stringFlavor);
			return getImportableDataName(s)!=null;
		} catch (Exception e) {
		}
   }
   return false;
}
 
Example 17
Source File: ImportCaReplyFromClipboardAction.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private X509Certificate[] openCaReply() {

		X509Certificate[] certs = null;

		try {

			// get clip board contents, but only string types, not files
			Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
			Transferable t = clipboard.getContents(null);
			if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
				String data;
				data = (String) t.getTransferData(DataFlavor.stringFlavor);

				// try to extract certs from clip board data
				certs = X509CertUtil.loadCertificates(data.getBytes());
				if (certs.length == 0) {
					JOptionPane.showMessageDialog(frame, MessageFormat.format(
							res.getString("ImportCaReplyFromClipboardAction.NoCertsFound.message"), "Clipboard"), res
							.getString("ImportCaReplyFromClipboardAction.OpenCaReply.Title"),
							JOptionPane.WARNING_MESSAGE);
				}
			}

			return certs;
		} catch (Exception ex) {
			String problemStr = MessageFormat.format(
					res.getString("ImportCaReplyFromClipboardAction.NoOpenCaReply.Problem"), "Clipboard");

			String[] causes = new String[] { res.getString("ImportCaReplyFromClipboardAction.NotCaReply.Cause"),
					res.getString("ImportCaReplyFromClipboardAction.CorruptedCaReply.Cause") };

			Problem problem = new Problem(problemStr, causes, ex);

			DProblem dProblem = new DProblem(frame,
					res.getString("ImportCaReplyFromClipboardAction.ProblemOpeningCaReply.Title"),
					problem);
			dProblem.setLocationRelativeTo(frame);
			dProblem.setVisible(true);

			return null;
		}
	}
 
Example 18
Source File: ClipboardHandler.java    From PolyGlot with MIT License 4 votes vote down vote up
/**
 * Tests whether the contents of clipboard is an image
 * @return true if image
 */
public static boolean isClipboardImage() {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable contents = clipboard.getContents(null);
    return contents.isDataFlavorSupported(DataFlavor.imageFlavor);
}
 
Example 19
Source File: FunctionGraphPlugin1Test.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Test
public void testCopyAction() {
	//
	// Put the cursor in a vertex on a field with text and make sure that the copy action
	// is enabled.
	//

	// 
	// Initialize the clipboard with known data
	//
	Clipboard systemClipboard = tool.getToolFrame().getToolkit().getSystemClipboard();
	systemClipboard.setContents(DUMMY_TRANSFERABLE, null);
	waitForSwing();

	//
	// Verify our initial state
	FGData graphData = getFunctionGraphData();
	assertNotNull(graphData);
	assertTrue("Unexpectedly received an empty FunctionGraphData", graphData.hasResults());
	ProgramLocation location = getLocationForAddressString(startAddressString);
	assertTrue(graphData.containsLocation(location));
	FunctionGraph functionGraph = graphData.getFunctionGraph();

	// locate vertex with cursor
	FGVertex focusedVertex = getFocusVertex(functionGraph);
	assertNotNull("We did not start with a focused vertex", focusedVertex);

	//
	// Put the cursor on a copyable thing
	//
	codeBrowser.goToField(getAddress("0x01004196"), "Mnemonic", 0, 0, 2, true);
	waitForSwing();

	// sanity check
	DockingAction copyAction = getCopyAction();
	assertClipboardServiceAddress(copyAction, "0x01004196");

	//
	// Validate and execute the action
	//		
	FGController controller = getFunctionGraphController();
	ComponentProvider provider = controller.getProvider();
	ActionContext actionContext = provider.getActionContext(null);
	boolean isEnabled = copyAction.isEnabledForContext(actionContext);
	debugAction(copyAction, actionContext);
	assertTrue(isEnabled);
	performAction(copyAction, actionContext, true);

	Transferable contents = systemClipboard.getContents(systemClipboard);
	assertNotNull(contents);
	assertTrue("Contents not copied into system clipboard", (contents != DUMMY_TRANSFERABLE));
}
 
Example 20
Source File: BaseCaret.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void mouseClicked(MouseEvent evt) {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("mouseClicked: " + logMouseEvent(evt) + ", state=" + mouseState + '\n'); // NOI18N
    }
    
    JTextComponent c = component;
    if (c != null) {
        if (isMiddleMouseButtonExt(evt)) {
            if (evt.getClickCount() == 1) {
                if (c == null) {
                    return;
                }
                Clipboard buffer = getSystemSelection();

                if (buffer == null) {
                    return;
                }

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

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

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

                try {
                    final String pastingString = (String) trans.getTransferData(DataFlavor.stringFlavor);
                    if (pastingString == null) {
                        return;
                    }
                    doc.runAtomicAsUser(new Runnable() {
                        public @Override
                        void run() {
                            try {
                                doc.insertString(offset, pastingString, null);
                                setDot(offset + pastingString.length());
                            } catch (BadLocationException exc) {
                            }
                        }
                    });
                } catch (UnsupportedFlavorException ufe) {
                } catch (IOException ioe) {
                }
            }
        }
    }
}