下面列出了怎么用java.awt.datatransfer.StringSelection的API类实例代码及写法,或者点击链接到github查看源代码。
public DraggableButton(final Action action) {
super(action);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent event) {
getTransferHandler().exportAsDrag(DraggableButton.this, event, TransferHandler.COPY);
}
});
t = new TransferHandler("graph") {
@Override
public Transferable createTransferable(final JComponent c) {
return new StringSelection("graphSelection");
}
};
setTransferHandler(t);
source = new DragSource();
source.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);
}
/**
* Creates a Copy Button
*
* @param text
* Text to copy into clipboard
* @return
*/
private static JButton makeCopyButton(String text) {
Action copyAction = new ResourceAction(true, "browser_unavailable.copy") {
private static final long serialVersionUID = 1L;
@Override
public void loggedActionPerformed(ActionEvent e) {
StringSelection stringSelection = new StringSelection(text);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
}
};
JButton copyButton = new JButton(copyAction);
return copyButton;
}
private void makeActions() {
exportKeysAction = new Action() {
@Override
public void run() {
List<Document> docs = (List<Document>) viewer.getInput();
String ret = "";
for (Document d : docs) {
ret += d.getKey() + ",";
}
ret = ret.substring(0, ret.length() - 1);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection s = new StringSelection(ret);
clipboard.setContents(s, null);
System.out.println(ret);
}
};
exportKeysAction.setText("Copy Keys");
exportKeysAction.setToolTipText("Copy Bibtex Keys to Clipboard");
exportKeysAction.setImageDescriptor(
PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().add(exportKeysAction);
}
@Override
@NbBundle.Messages("LBL_CopyStackTrace=&Copy Stack Trace")
public Action[] getActions(boolean context) {
List<Action> actions = new ArrayList<Action>();
if ((testcase.getTrouble() != null) && (testcase.getTrouble().getComparisonFailure() != null)){
actions.add(new DiffViewAction(testcase));
}
if (testcase.getTrouble() != null && testcase.getTrouble().getStackTrace() != null) {
StringBuilder callStack = new StringBuilder();
for(String stack : testcase.getTrouble().getStackTrace()) {
if(stack != null) {
callStack.append(stack.concat("\n"));
}
}
if (callStack.length() > 0) {
final String trace = callStack.toString();
actions.add(new AbstractAction(Bundle.LBL_CopyStackTrace()) {
@Override
public void actionPerformed(ActionEvent e) {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(trace), null);
}
});
}
}
return actions.toArray(new Action[actions.size()]);
}
@Override
public void exec(String input) {
if (!this.clamp(input, 1, 1)) {
this.printUsage();
return;
}
final Minecraft mc = Minecraft.getMinecraft();
if(mc.getCurrentServerData() != null) {
final StringSelection contents = new StringSelection(mc.getCurrentServerData().serverIP);
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(contents, null);
Seppuku.INSTANCE.logChat("Copied IP to clipboard");
}else{
Seppuku.INSTANCE.errorChat("Error, Join a server");
}
}
private boolean copyToInternalClipboard() {
List<Note> selection = getSelectedNotes();
StringBuilder b = new StringBuilder();
int cnt = 0;
for (Note a : selection) {
b.append(Note.toInternalRepresentation(a)).append("\n");
cnt++;
}
try {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b.toString()), null);
showSuccess(cnt + ((cnt == 1) ? " Notiz kopiert" : " Notizen kopiert"));
return true;
} catch (HeadlessException hex) {
showError("Fehler beim Kopieren der Notizen");
}
return false;
}
protected final void htmlMinify(final Node[] activatedNodes) {
final EditorCookie editorCookie
= Utilities.actionsGlobalContext().lookup(EditorCookie.class);
for (final JEditorPane pane : editorCookie.getOpenedPanes()) {
if (pane.isShowing()
&& pane.getSelectionEnd() > pane.getSelectionStart()) {
try {
StringSelection content = new StringSelection(selectedSourceAsMinify(pane));
Toolkit.getDefaultToolkit().getSystemClipboard().
setContents(content, content);
return;
} catch (final HeadlessException e) {
org.openide.ErrorManager.getDefault().notify(e);
}
}
}
}
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);
}
@Override
public Transferable clipboardCopy() {
String result = "";
PayaraModule commonModule = lu.lookup(PayaraModule.class);
if (commonModule != null) {
Map<String, String> ip = commonModule.getInstanceProperties();
String host = ip.get(PayaraModule.HTTPHOST_ATTR);
if (null == host) {
host = ip.get(PayaraModule.HOSTNAME_ATTR);
}
String httpPort = ip.get(PayaraModule.HTTPPORT_ATTR);
String url = ip.get(PayaraModule.URL_ATTR);
if (url == null || !url.contains("ee6wc")) {
result = Utils.getHttpListenerProtocol(host, httpPort)
+ "://" + host + ":" + httpPort + "/" + ws.getTestURL();
} else {
result = "http"
+ "://" + host + ":" + httpPort + "/" + ws.getTestURL();
}
if (result.endsWith("//")) {
result = result.substring(0, result.length() - 1);
}
}
return new StringSelection(result);
}
private void copy() {
StringBuilder strBuffer = new StringBuilder();
int numcols = insertRecordTableUI.getSelectedColumnCount();
int numrows = insertRecordTableUI.getSelectedRowCount();
int[] rowsselected = insertRecordTableUI.getSelectedRows();
int[] colsselected = insertRecordTableUI.getSelectedColumns();
if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] && numrows == rowsselected.length) &&
(numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] && numcols == colsselected.length))) {
JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
return;
}
for (int i = 0; i < numrows; i++) {
for (int j = 0; j < numcols; j++) {
strBuffer.append(insertRecordTableUI.getValueAt(rowsselected[i], colsselected[j]));
if (j < numcols - 1) {
strBuffer.append("\t");
}
}
strBuffer.append("\n");
}
StringSelection stringSelection = new StringSelection(strBuffer.toString());
clipBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipBoard.setContents(stringSelection, stringSelection);
}
public void actionPerformed(ActionEvent event) {
ViewerBase viewer = (ViewerBase) getViewer();
StringBuilder buf = new StringBuilder();
boolean first = true;
for (String label : viewer.getSelectedNodeLabels(true)) {
if (label != null) {
if (first)
first = false;
else
buf.append(" ");
buf.append(label);
}
}
if (buf.toString().length() > 0) {
StringSelection selection = new StringSelection(buf.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
}
}
public static void setClipBoardAndUpdate(String text)
{
try
{
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
}catch(IllegalStateException e)
{
try
{
Thread.sleep(1);
} catch (InterruptedException ignored) {}
setClipBoardAndUpdate(text);//try again later
}
}
/**
* This method combines the list of usernames on local players friend/ignore list into a comma delimited string
* and then copies it to the clipboard.
*/
private void friendIgnoreToClipboard()
{
StringBuilder friendsList = new StringBuilder();
NameableContainer<Friend> friendContainer = client.getFriendContainer();
NameableContainer<Ignore> ignoreContainer = client.getIgnoreContainer();
String[] friendsIgnores = ArrayUtils.addAll(Arrays.stream(friendContainer.getMembers()).map(Nameable::getName).toArray(String[]::new),
Arrays.stream(ignoreContainer.getMembers()).map(Nameable::getName).toArray(String[]::new));
HashSet<String> names = new HashSet<>(Arrays.asList(friendsIgnores));
names.forEach(n -> friendsList.append(n.toLowerCase()).append(","));
StringSelection namesSelection = new StringSelection(friendsList.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(namesSelection, namesSelection);
}
private static void writeToClipboard(String text, String successMessage) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection output = new StringSelection(text);
try {
clipboard.setContents(output, output);
SkyblockAddons.getInstance().getUtils().sendMessage(successMessage);
} catch (IllegalStateException exception) {
SkyblockAddons.getInstance().getUtils().sendErrorMessage("Clipboard not available.");
}
}
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showOptionDialog(PreferencesFrame.this,
"Are you sure you want to uninstall " + plugin.getShortDescription() + "?" +
"\n\nNo files will be deleted from your computer.", "",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
new Object[] { "Uninstall", "Cancel" }, "Cancel");
if (result == 0) {
if (!GUISaveState.getInstance().removeCustomPlugin(url)) {
if ("file".equals(url.getProtocol())) {
String path = url.toExternalForm();
try {
path = new File(URLDecoder.decode(url.getPath(), "UTF-8")).getAbsolutePath();
} catch (UnsupportedEncodingException ex) {
}
try {
StringSelection contents = new StringSelection(path);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(contents, contents);
} catch (Exception e1) {
}
JOptionPane.showMessageDialog(PreferencesFrame.this,
"The plugin could not be uninstalled automatically.\n\n" +
"You can try to delete this plugin manually: \n"
+ path + "\n\n(This path has been copied to your clipboard)",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(PreferencesFrame.this,
"This plugin is not actually in the list of plugins...\n" +
"Not sure what to do...\n "
+ url.toExternalForm()
+ "\n\nPlugin URL's:\n" +
GUISaveState.getInstance().getCustomPlugins(),
"Error", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(PreferencesFrame.this,
"Changes will take effect after you restart SpotBugs.");
}
}
}
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, 5));
header.setOpaque(false);
header.add(new JLabel(MessageUtils.getLocalizedMessage("documents.stored.label.stored_value")));
header.add(new JLabel(field));
panel.add(header, BorderLayout.PAGE_START);
JTextArea valueTA = new JTextArea(value);
valueTA.setLineWrap(true);
valueTA.setEditable(false);
valueTA.setBackground(Color.white);
JScrollPane scrollPane = new JScrollPane(valueTA);
panel.add(scrollPane, 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(value);
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;
}
@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 copyToClipboard() {
// 選択されている行を取得
final int[] selectedRows = getSelection();
if (selectedRows.length == 0) {
return;
}
final StringBuilder builder = new StringBuilder();
// 全てが選択されている場合はヘッダもコピー
// if (selectedRows.length == this.editColumnTable.getItemCount()) {
// for (TableColumn c : this.editColumnTable.getColumns()) {
// builder.append(c.getText());
// builder.append("\t");
// }
// builder.deleteCharAt(builder.length() - 1);
// builder.append("\r\n");
// }
final int columnCount = getColumnCount();
for (final int selectedRow : selectedRows) {
for (int column = 0; column < columnCount; column++) {
final Object value = getValueAt(selectedRow, column);
builder.append(Format.toString(value));
builder.append("\t");
}
builder.deleteCharAt(builder.length() - 1);
builder.append("\r\n");
}
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection(builder.toString()), this);
}
@Override
public void doCopy() {
StringWriter writer = new StringWriter();
PrintWriter pwriter = new PrintWriter(writer);
for (String tip : tempestPanel.getSelectedTips()) {
pwriter.println(tip);
}
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection selection = new StringSelection(writer.toString());
clipboard.setContents(selection, selection);
}
@Override
protected Transferable createTransferable( JComponent c ) {
if( c instanceof JList && ((JList<?>)c).isSelectionEmpty() )
return null;
if( c instanceof JTree && ((JTree)c).isSelectionEmpty() )
return null;
if( c instanceof JTable && ((JTable)c).getSelectionModel().isSelectionEmpty() )
return null;
return new StringSelection( "dummy" );
}
public void update () {
System.out.println(Tools.bytesToHex(Main.node.pubKeyServer.getPubKey()));
if (secret == null) {
secret = new PaymentSecret(Tools.getRandomByte(20));
Main.dbHandler.addPaymentSecret(secret);
System.out.println("HASH: "+Tools.bytesToHex(secret.hash));
}
try {
byte[] payload = getPayload();
FieldAddress.setText(Tools.bytesToHex(payload));
FieldHash.setText(Tools.bytesToHex(secret.hash));
System.out.println(Tools.bytesToHex(payload));
final byte[] imageBytes = QRCode
.from(Tools.bytesToHex(payload))
.withSize(250, 250)
.to(ImageType.PNG)
.stream()
.toByteArray();
Image qrImage = new Image(new ByteArrayInputStream(imageBytes));
ImageQR.setImage(qrImage);
ImageQR.setEffect(new DropShadow());
StringSelection stringSelection = new StringSelection(Tools.bytesToHex(payload));
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 把文本设置到剪贴板(复制)
*
* @param text the text
*/
public static void setStringToClipboard(String text) {
// 获取系统剪贴板
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
// 封装文本内容
Transferable trans = new StringSelection(text);
// 把文本内容设置到系统剪贴板
clipboard.setContents(trans, null);
}
public void putBoundingBox(BoundingBox bbox) {
StringBuilder content = new StringBuilder();
content.append("bbox=")
.append(bbox.getLowerCorner().getX()).append(",")
.append(bbox.getLowerCorner().getY()).append(",")
.append(bbox.getUpperCorner().getX()).append(",")
.append(bbox.getUpperCorner().getY());
if (bbox.isSetSrs()) {
content.append("&3dcitydb_srs=")
.append(bbox.getSrs().getId());
}
systemClipboard.setContents(new StringSelection(content.toString()), this);
}
private void copyDefRequests() {
REFTargetElement[] selection = getSelectedElements();
if (selection.length == 0) {
jStatusLabel.setText("Keine Einträge gewählt");
return;
}
boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this, "Erweiterte BB-Codes verwenden (nur für Forum und Notizen geeignet)?", "Erweiterter BB-Code", "Nein", "Ja") == JOptionPane.YES_OPTION);
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm:ss");
StringBuilder b = new StringBuilder();
b.append("Ich benötige die aufgelisteten oder vergleichbare Unterstützungen in den folgenden Dörfern:\n\n");
TroopAmountFixed split = splitAmountPanel.getAmounts();
for (REFTargetElement defense : selection) {
Village target = defense.getVillage();
int needed = defense.getNeededSupports();
TroopAmountFixed need = new TroopAmountFixed();
for (UnitHolder unit: DataHolder.getSingleton().getUnits()) {
need.setAmountForUnit(unit, needed * split.getAmountForUnit(unit));
}
if (extended) {
b.append("[table]\n");
b.append("[**]").append(target.toBBCode()).append("[|]");
b.append("[img]").append(UnitTableInterface.createDefenderUnitTableLink(need)).append("[/img][/**]\n");
b.append("[/table]\n");
} else {
b.append(buildSimpleRequestTable(target, need, defense));
}
}
try {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b.toString()), null);
jStatusLabel.setText("Unterstützungsanfragen in die Zwischenablage kopiert");
} catch (HeadlessException hex) {
jStatusLabel.setText("Fehler beim Kopieren in die Zwischenablage");
}
}
protected void copy(int row, Point toastPoint /* mmmmm.... toast points */) {
AttributeDefinition definition = model.getValue(row);
String name = getAttributeName(definition);
Object value = getValue(name);
StringSelection selection = new StringSelection(getCopyValue(definition, name, value));
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
Toast.showToast(table, "Copied to Clipboard", toastPoint, 1000);
}
@Override
public void keyReleased(KeyEvent e) {
if (e.isControlDown()) {
if (e.getKeyCode() == KeyEvent.VK_C) { // Copy
List<TreePath> v = Arrays.asList(((Tree) e.getComponent()).getSelectionModel().getSelectionPaths());
String str = SerialisationHelper.convertToCsv(v);
StringSelection selection = new StringSelection(str);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (globals.get(Traits.class).isAvailable("4.0.x")) {
StringSelection s = new StringSelection(panel.getContentString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
}
else {
globals.get(LifecycleManager.class).sendBusMessage(new JTextField());
}
}
private void copyValues() {
List<String> values = valueList.getSelectedValuesList();
if (values.isEmpty()) {
values = getAllVlues();
}
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection selection = new StringSelection(String.join("\n", values));
clipboard.setContents(selection, null);
}
/**
* Copies the selected tasks names to the clipboard
*/
private void copySelectedTaskNames() {
String names = getSelectedTaskNames();
if (names.length() == 0) {
return;
}
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(names), null);
}
@Override
protected void actionPerformedInBlazeProject(Project project, AnActionEvent e) {
Label label = findTarget(project, e);
if (label != null) {
CopyPasteManager.getInstance().setContents(new StringSelection(label.toString()));
}
}