Java Code Examples for java.awt.datatransfer.Clipboard

The following examples show how to use java.awt.datatransfer.Clipboard. These examples are extracted from open source projects. 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 Project: gepard   Author: univieCUBE   File: ClientGlobals.java    License: MIT License 6 votes vote down vote up
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);

}
 
Example #2
Source Project: netbeans   Author: apache   File: OutlineView.java    License: Apache License 2.0 6 votes vote down vote up
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
        }
    }                        
}
 
Example #3
Source Project: Logisim   Author: LogisimIt   File: Clip.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #4
Source Project: Digital   Author: hneemann   File: CircuitComponent.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #5
Source Project: keystore-explorer   Author: kaikramer   File: DErrorDetail.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #6
Source Project: netbeans   Author: apache   File: DebuggingJSActionsProvider.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #7
Source Project: ganttproject   Author: bardsoftware   File: PasteAction.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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();
    }
  }
}
 
Example #8
Source Project: nullpomino   Author: nullpomino   File: NetAdmin.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example #9
Source Project: TencentKona-8   Author: Tencent   File: bug8059739.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #10
Source Project: netbeans   Author: apache   File: DebuggingActionsProvider.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #11
Source Project: netbeans-mmd-plugin   Author: raydac   File: AbstractPlUmlEditor.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #12
Source Project: tracker   Author: OpenSourcePhysics   File: TToolBar.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source Project: jdk8u60   Author: chenghanpeng   File: bug8059739.java    License: GNU General Public License v2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #14
Source Project: lucene-solr   Author: apache   File: DocumentsPanelProvider.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #15
Source Project: knife   Author: bit4woo   File: RobotInput.java    License: MIT License 5 votes vote down vote up
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。
	}
 
Example #16
Source Project: netbeans   Author: apache   File: PasteAction.java    License: Apache License 2.0 5 votes vote down vote up
/** 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;
}
 
Example #17
Source Project: lucene-solr   Author: apache   File: ExplainDialogFactory.java    License: Apache License 2.0 5 votes vote down vote up
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("&#xe0e6;", 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;
}
 
Example #18
Source Project: netbeans-mmd-plugin   Author: raydac   File: MMDGraphEditor.java    License: Apache License 2.0 5 votes vote down vote up
private void registerAsClipboardListener() {
  final Clipboard clipboard = NbUtils.findClipboard();
  if (clipboard instanceof ExClipboard) {
    ((ExClipboard) clipboard).addClipboardListener(this);
  } else {
    clipboard.addFlavorListener(this);
  }
  processClipboardChange(clipboard);
}
 
Example #19
Source Project: netbeans-mmd-plugin   Author: raydac   File: AbstractPlUmlEditor.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #20
Source Project: htmlunit   Author: HtmlUnit   File: DoTypeProcessor.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #21
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: XToolkit.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #22
Source Project: otroslogviewer   Author: otros-systems   File: ParseClipboard.java    License: Apache License 2.0 5 votes vote down vote up
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");
  }
}
 
Example #23
Source Project: netbeans-mmd-plugin   Author: raydac   File: FreeMindExporter.java    License: Apache License 2.0 5 votes vote down vote up
@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);
      }
    }
  });
}
 
Example #24
Source Project: dragonwell8_jdk   Author: alibaba   File: XToolkit.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #25
Source Project: basicv2   Author: EgonOlsen71   File: ShellTextComponent.java    License: 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 #26
Source Project: netbeans-mmd-plugin   Author: raydac   File: MDExporter.java    License: Apache License 2.0 5 votes vote down vote up
@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);
      }
    }
  });
}
 
Example #27
Source Project: keystore-explorer   Author: kaikramer   File: DViewAsn1Dump.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void copyPressed() {
	String policy = jtaAsn1Dump.getText();

	Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	StringSelection copy = new StringSelection(policy);
	clipboard.setContents(copy, copy);
}
 
Example #28
Source Project: rapidminer-studio   Author: rapidminer   File: ProcessPanel.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source Project: netbeans   Author: apache   File: DragDropUtilities.java    License: Apache License 2.0 5 votes vote down vote up
/** 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;
    }
}
 
Example #30
Source Project: ghidra   Author: NationalSecurityAgency   File: AboutDomainObjectUtils.java    License: Apache License 2.0 5 votes vote down vote up
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.");
	}
}