下面列出了怎么用java.awt.datatransfer.Clipboard的API类实例代码及写法,或者点击链接到github查看源代码。
public static void unexpectedError(Exception e, Controller ctrl) {
// handles any unexpected errors
// asks the user to send an error report to the developer
String guidump = ctrl.getGUIDump();
String msg;
msg = "An unexpected error occured!\nStack trace & GUI details copied to clipboard.";
JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.ERROR_MESSAGE);
String report = stack2string(e) + "\n\n\n\n" + guidump;
StringSelection stringSelection = new StringSelection (report);
Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);
}
private void doCopy(ExplorerManager em) {
Node[] sel = em.getSelectedNodes();
Transferable trans = ExplorerActionsImpl.getTransferableOwner(sel, true);
Transferable ot = new OutlineTransferHandler().createOutlineTransferable();
if (trans != null) {
if (ot != null) {
trans = new TextAddedTransferable(trans, ot);
}
} else {
trans = ot;
}
if (trans != null) {
Clipboard clipboard = ExplorerActionsImpl.getClipboard();
if (clipboard != null) {
clipboard.setContents(trans, new StringSelection("")); // NOI18N
}
}
}
public void copy() {
Caret caret = editor.getCaret();
long p0 = caret.getMark();
long p1 = caret.getDot();
if (p0 < 0 || p1 < 0)
return;
if (p0 > p1) {
long t = p0;
p0 = p1;
p1 = t;
}
p1++;
int[] data = new int[(int) (p1 - p0)];
HexModel model = editor.getModel();
for (long i = p0; i < p1; i++) {
data[(int) (i - p0)] = model.get(i);
}
Clipboard clip = editor.getToolkit().getSystemClipboard();
clip.setContents(new Data(data), this);
}
private ToolTipAction createPasteAction(ShapeFactory shapeFactory) {
return new ToolTipAction(Lang.get("menu_paste")) {
@Override
public void actionPerformed(ActionEvent e) {
if (!isLocked()) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
Object data = clipboard.getData(DataFlavor.stringFlavor);
if (data instanceof String) {
Vector posVector = getPosVector(lastMousePos.x, lastMousePos.y);
ArrayList<Movable> elements = CircuitTransferable.createList(data, shapeFactory);
if (elements != null)
setPartsToInsert(elements, posVector);
}
} catch (Exception e1) {
e1.printStackTrace();
SwingUtilities.invokeLater(new ErrorMessage(Lang.get("msg_clipboardContainsNoImportableData")).setComponent(CircuitComponent.this));
}
}
}
}.setAcceleratorCTRLplus('V').enableAcceleratorIn(this);
}
private void copyPressed() {
StringBuffer strBuff = new StringBuffer();
Throwable copyError = error;
while (copyError != null) {
strBuff.append(copyError);
strBuff.append('\n');
for (StackTraceElement stackTrace : copyError.getStackTrace()) {
strBuff.append("\tat ");
strBuff.append(stackTrace);
strBuff.append('\n');
}
copyError = copyError.getCause();
if (copyError != null) {
strBuff.append('\n');
}
}
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection copy = new StringSelection(strBuff.toString());
clipboard.setContents(copy, copy);
}
private void stackToCLBD(List<JPDAThread> threads) {
StringBuffer frameStr = new StringBuffer(512);
for (JPDAThread t : threads) {
if (frameStr.length() > 0) {
frameStr.append('\n');
}
frameStr.append("\"");
frameStr.append(t.getName());
frameStr.append("\"\n");
appendStackInfo(frameStr, t);
}
Clipboard systemClipboard = getClipboard();
Transferable transferableText =
new StringSelection(frameStr.toString());
systemClipboard.setContents(
transferableText,
null);
}
@Override
public void actionPerformed(ActionEvent evt) {
if (calledFromAppleScreenMenu(evt)) {
return;
}
ChartSelection selection = myViewmanager.getSelectedArtefacts();
if (!selection.isEmpty()) {
pasteInternalFlavor(selection);
return;
}
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clipboard.isDataFlavorAvailable(GPTransferable.EXTERNAL_DOCUMENT_FLAVOR)) {
try {
Object data = clipboard.getData(GPTransferable.EXTERNAL_DOCUMENT_FLAVOR);
if (data instanceof InputStream == false) {
return;
}
pasteExternalDocument((InputStream) data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Copy the selected row to clipboard
* @param table JTable
*/
private static void copyTableRowToClipboard(final JTable table) {
int row = table.getSelectedRow();
if(row != -1) {
String strCopy = "";
for(int column = 0; column < table.getColumnCount(); column++) {
Object selectedObject = table.getValueAt(row, column);
if(selectedObject instanceof String) {
if(column == 0) {
strCopy += (String)selectedObject;
} else {
strCopy += "," + (String)selectedObject;
}
}
}
StringSelection ss = new StringSelection(strCopy);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(ss, ss);
}
}
private static void runTest() throws Exception {
String testString = "my string";
JTextField tf = new JTextField(testString);
tf.selectAll();
Clipboard clipboard = new Clipboard("clip");
tf.getTransferHandler().exportToClipboard(tf, clipboard, TransferHandler.COPY);
DataFlavor[] dfs = clipboard.getAvailableDataFlavors();
for (DataFlavor df: dfs) {
String charset = df.getParameter("charset");
if (InputStream.class.isAssignableFrom(df.getRepresentationClass()) &&
charset != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(
(InputStream) clipboard.getData(df), charset));
String s = br.readLine();
System.out.println("Content: '" + s + "'");
passed &= s.contains(testString);
}
}
}
static void stackToCLBD(List<JPDAThread> threads) {
StringBuffer frameStr = new StringBuffer(512);
for (JPDAThread t : threads) {
if (frameStr.length() > 0) {
frameStr.append('\n');
}
frameStr.append("\"");
frameStr.append(t.getName());
frameStr.append("\"\n");
appendStackInfo(frameStr, t);
}
Clipboard systemClipboard = getClipboard();
Transferable transferableText =
new StringSelection(frameStr.toString());
systemClipboard.setContents(
transferableText,
null);
}
@Override
public boolean doPaste() {
boolean result = false;
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String text = null;
try {
if (Utils.isDataFlavorAvailable(clipboard, DataFlavor.stringFlavor)) {
text = clipboard.getData(DataFlavor.stringFlavor).toString();
}
} catch (Exception ex) {
logger.warn("Can't get data from clipboard : " + ex.getMessage()); //NOI18N
}
if (text != null) {
this.editor.replaceSelection(text);
result = true;
}
return result;
}
/**
* Refreshes and returns the "new tracks" popup menu.
*
* @return the popup
*/
protected JPopupMenu getNewTracksPopup() {
newPopup.removeAll();
TMenuBar menubar = TMenuBar.getMenuBar(trackerPanel);
menubar.refresh();
for (Component c: menubar.newTrackItems) {
newPopup.add(c);
if (c==menubar.newDataTrackMenu) {
// disable newDataTrackPasteItem unless pastable data is on the clipboard
menubar.newDataTrackPasteItem.setEnabled(false);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable data = clipboard.getContents(null);
if (data != null && data.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
String s = (String)data.getTransferData(DataFlavor.stringFlavor);
menubar.newDataTrackPasteItem.setEnabled(ParticleDataTrack.getImportableDataName(s)!=null);
} catch (Exception ex) {}
}
}
}
if (menubar.cloneMenu.getItemCount()>0 && trackerPanel.isEnabled("new.clone")) { //$NON-NLS-1$
newPopup.addSeparator();
newPopup.add(menubar.cloneMenu);
}
return newPopup;
}
private static void runTest() throws Exception {
String testString = "my string";
JTextField tf = new JTextField(testString);
tf.selectAll();
Clipboard clipboard = new Clipboard("clip");
tf.getTransferHandler().exportToClipboard(tf, clipboard, TransferHandler.COPY);
DataFlavor[] dfs = clipboard.getAvailableDataFlavors();
for (DataFlavor df: dfs) {
String charset = df.getParameter("charset");
if (InputStream.class.isAssignableFrom(df.getRepresentationClass()) &&
charset != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(
(InputStream) clipboard.getData(df), charset));
String s = br.readLine();
System.out.println("Content: '" + s + "'");
passed &= s.contains(testString);
}
}
}
private void copySelectedOrAllStoredValues() {
StringSelection selection;
if (documentTable.getSelectedRowCount() == 0) {
selection = copyAllValues();
} else {
selection = copySelectedValues();
}
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
messageBroker.clearStatusMessage();
}
public final String getSelectedString(){
try {
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();//获取剪切板
Transferable origin = clip.getContents(null);//备份之前剪切板的内容
String selectedString = (String)clip.getData(DataFlavor.stringFlavor);
System.out.println("复制之前剪切板中的内容:"+selectedString);
inputWithCtrl(KeyEvent.VK_C);
final String result = (String)clip.getData(DataFlavor.stringFlavor);
//selectedString = (String)clip.getData(DataFlavor.stringFlavor);
System.out.println("复制之后剪切板中的内容:"+result);
clip.setContents(origin, null);//恢复之前剪切板的内容
selectedString = (String)clip.getData(DataFlavor.stringFlavor);
System.out.println("恢复之后剪切板中的内容:"+selectedString);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
// 复制之前剪切板中的内容:printStackTrace
// 复制之后剪切板中的内容:null
// 恢复之后剪切板中的内容:printStackTrace
// printStackTrace//最后的值随着剪切板的恢复而改变了,应该是引用传递的原因。所有需要将复制后的值设置为final。
}
/** If our clipboard is not found return the default system clipboard. */
private static Clipboard getClipboard() {
Clipboard c = Lookup.getDefault().lookup(Clipboard.class);
if (c == null) {
c = Toolkit.getDefaultToolkit().getSystemClipboard();
}
return c;
}
private JPanel content() {
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(false);
panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JPanel header = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 10));
header.setOpaque(false);
header.add(new JLabel(MessageUtils.getLocalizedMessage("search.explanation.description")));
header.add(new JLabel(String.valueOf(docid)));
panel.add(header, BorderLayout.PAGE_START);
JPanel center = new JPanel(new GridLayout(1, 1));
center.setOpaque(false);
center.add(new JScrollPane(createExplanationTree()));
panel.add(center, BorderLayout.CENTER);
JPanel footer = new JPanel(new FlowLayout(FlowLayout.TRAILING, 5, 5));
footer.setOpaque(false);
JButton copyBtn = new JButton(FontUtils.elegantIconHtml("", MessageUtils.getLocalizedMessage("button.copy")));
copyBtn.setMargin(new Insets(3, 3, 3, 3));
copyBtn.addActionListener(e -> {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection selection = new StringSelection(explanationToString());
clipboard.setContents(selection, null);
});
footer.add(copyBtn);
JButton closeBtn = new JButton(MessageUtils.getLocalizedMessage("button.close"));
closeBtn.setMargin(new Insets(3, 3, 3, 3));
closeBtn.addActionListener(e -> dialog.dispose());
footer.add(closeBtn);
panel.add(footer, BorderLayout.PAGE_END);
return panel;
}
private void registerAsClipboardListener() {
final Clipboard clipboard = NbUtils.findClipboard();
if (clipboard instanceof ExClipboard) {
((ExClipboard) clipboard).addClipboardListener(this);
} else {
clipboard.addFlavorListener(this);
}
processClipboardChange(clipboard);
}
@Override
public boolean doCopy() {
boolean result = false;
final String selected = this.editor.getSelectedText();
if (selected != null && !selected.isEmpty()) {
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection(selected), null);
}
return result;
}
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;
}
public Clipboard getSystemSelection() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(SecurityConstants.AWT.ACCESS_CLIPBOARD_PERMISSION);
}
synchronized (this) {
if (selection == null) {
selection = new XClipboard("Selection", "PRIMARY");
}
}
return selection;
}
private void updateFromClipboard(Clipboard systemClipboard, JTextArea textArea) {
final Optional<String> maybeContent = getStringFromClipboard(systemClipboard);
if (maybeContent.isPresent()) {
textArea.setText(maybeContent.get());
textArea.setCaretPosition(0);
} else {
textArea.setText("");
statusLabel.setIcon(Icons.STATUS_ERROR);
statusLabel.setText("Clipboard content is not text");
}
}
@Override
public void doExportToClipboard(@Nonnull final PluginContext context, @Nonnull final JComponent options) throws IOException {
final String text = makeContent(context.getPanel());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clipboard != null) {
clipboard.setContents(new StringSelection(text), null);
}
}
});
}
public Clipboard getSystemClipboard() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(SecurityConstants.AWT.ACCESS_CLIPBOARD_PERMISSION);
}
synchronized (this) {
if (clipboard == null) {
clipboard = new XClipboard("System", "CLIPBOARD");
}
}
return clipboard;
}
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");
}
@Override
public void doExportToClipboard(@Nonnull final PluginContext context, @Nonnull final JComponent options) throws IOException {
final String text = makeContent(context.getPanel());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clipboard != null) {
clipboard.setContents(new StringSelection(text), null);
}
}
});
}
private void copyPressed() {
String policy = jtaAsn1Dump.getText();
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection copy = new StringSelection(policy);
clipboard.setContents(copy, copy);
}
/**
* Looks through the file list for the first file with .rmp file extension and returns its content as a String. If
* there is no such file, {@code null} is returned instead.
*
* @param clipBoard
* Clipboard holding a file list.
* @return XML process definition or {@code null}.
*/
private static String loadProcessFromFileList(Clipboard clipBoard, MainFrame mainFrame) throws IOException, UnsupportedFlavorException {
@SuppressWarnings("unchecked") // we did the check in firePasteProcess - the cast is safe
List<File> fileList = ((List<File>) clipBoard.getContents(mainFrame.getProcessPanel()).getTransferData(DataFlavor.javaFileListFlavor));
for (File file : fileList) {
if (RapidMiner.PROCESS_FILE_EXTENSION.equals(FilenameUtils.getExtension(file.getName()))) {
return new String(Files.readAllBytes(file.toPath()));
}
}
return null;
}
/** Gets right transferable of given nodes (according to given
* drag action) and also converts the transferable.<br>
* Can be called only with correct action constant.
* @return The transferable.
*/
static Transferable getNodeTransferable(Node[] nodes, int dragAction)
throws IOException {
Transferable[] tArray = new Transferable[nodes.length];
for (int i = 0; i < nodes.length; i++) {
if ((dragAction & DnDConstants.ACTION_MOVE) != 0) {
tArray[i] = nodes[i].clipboardCut();
} else {
tArray[i] = nodes[i].drag ();
}
}
Transferable result;
if (tArray.length == 1) {
// only one node, so return regular single transferable
result = tArray[0];
} else {
// enclose the transferables into multi transferable
result = ExternalDragAndDrop.maybeAddExternalFileDnd( new Multi(tArray) );
}
Clipboard c = getClipboard();
if (c instanceof ExClipboard) {
return ((ExClipboard) c).convert(result);
} else {
return result;
}
}
private static void writeDataToClipboard(Component component) {
Clipboard systemClipboard = GClipboard.getSystemClipboard();
try {
systemClipboard.setContents(createContents(component), null);
}
catch (IllegalStateException e) {
Msg.showInfo(AboutDomainObjectUtils.class, null, "Cannot Copy Data",
"Unable to copy information to clipboard. Please try again.");
}
}