Java/Development Class/Clip Board
Содержание
- 1 Communicating with the System Clipboard
- 2 Copying data to system clipboard
- 3 Determining When an Item Is No Longer on the System Clipboard
- 4 Get string value from clipboard
- 5 Getting and Setting an Image on the System Clipboard
- 6 Getting data from the computer clipboard
- 7 implements ClipboardOwner
- 8 Placing text on the computer clipboard
- 9 Sending Image Objects through the Clipboard
- 10 Setting an image on the clipboard with a custom Transferable object to hold the image
- 11 Taken from the Sun documentation on Clipboard API
- 12 Using the clipboard
- 13 Write a string to the system clipboard
Communicating with the System Clipboard
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ClipText {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
final Clipboard clipboard = frame.getToolkit().getSystemClipboard();
final JTextArea jt = new JTextArea();
JScrollPane pane = new JScrollPane(jt);
contentPane.add(pane, BorderLayout.CENTER);
JButton copy = new JButton("Copy");
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selection = jt.getSelectedText();
StringSelection data = new StringSelection(selection);
clipboard.setContents(data, data);
}
});
JButton paste = new JButton("Paste");
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Transferable clipData = clipboard.getContents(clipboard);
if (clipData != null) {
try {
if (clipData
.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String s = (String) (clipData
.getTransferData(DataFlavor.stringFlavor));
jt.replaceSelection(s);
}
} catch (UnsupportedFlavorException ufe) {
System.err.println("Unsupported flavor: " + ufe);
} catch (IOException ufe) {
System.err.println("Unable to get data: " + ufe);
}
}
}
});
JPanel p = new JPanel();
p.add(copy);
p.add(paste);
contentPane.add(p, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.show();
}
}
Copying data to system clipboard
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
public class Main {
public static void main(String[] argv) throws Exception {
}
// This method writes a string to the system clipboard.
public static void copyToSystemClipboard(String str) {
StringSelection ss = new StringSelection(str);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}
}
Determining When an Item Is No Longer on the System Clipboard
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
public class Main {
public static void main(String[] argv) throws Exception {
ClipboardOwner owner = new MyClipboardOwner();
StringSelection ss = new StringSelection("A String");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, owner);
}
}
class MyClipboardOwner implements ClipboardOwner {
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("lost");
}
}
Get string value from clipboard
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
public class Main {
public static void main(String[] argv) {
System.out.println(getClipboard());
}
public static String getClipboard() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String text = (String) t.getTransferData(DataFlavor.stringFlavor);
return text.trim();
}
} catch (Exception e) {
}
return "";
}
}
Getting and Setting an Image on the System Clipboard
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
public class Main {
public static void main(String[] argv) throws Exception {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
Image img = (Image) t.getTransferData(DataFlavor.imageFlavor);
}
}
}
Getting data from the computer clipboard
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
public class Main {
public static void main(String[] args) throws Exception {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tran = clipboard.getContents(null);
if (tran != null && tran.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String clipboardContent = (String) tran.getTransferData(DataFlavor.stringFlavor);
System.out.println(clipboardContent);
}
}
}
implements ClipboardOwner
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
public class Main {
public static void main(String[] argv) throws Exception {
ClipboardOwner owner = new MyClipboardOwner();
StringSelection ss = new StringSelection("A String");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, owner);
}
}
class MyClipboardOwner implements ClipboardOwner {
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("lost");
}
}
Placing text on the computer clipboard
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
public class Main {
public static void main(String[] args) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection("string"), null);
}
}
Sending Image Objects through the Clipboard
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Image;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;
public class ClipImage {
public static void main(String args[]) {
JFrame frame = new JFrame("Clip Image");
Container contentPane = frame.getContentPane();
final Clipboard clipboard = frame.getToolkit().getSystemClipboard();
Icon icon = new ImageIcon("jaeger.jpg");
final JLabel label = new JLabel(icon);
label.setTransferHandler(new ImageSelection());
JScrollPane pane = new JScrollPane(label);
contentPane.add(pane, BorderLayout.CENTER);
JButton copy = new JButton("Copy");
copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TransferHandler handler = label.getTransferHandler();
handler.exportToClipboard(label, clipboard,
TransferHandler.COPY);
}
});
JButton clear = new JButton("Clear");
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
label.setIcon(null);
}
});
JButton paste = new JButton("Paste");
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Transferable clipData = clipboard.getContents(clipboard);
if (clipData != null) {
if (clipData.isDataFlavorSupported(DataFlavor.imageFlavor)) {
TransferHandler handler = label.getTransferHandler();
handler.importData(label, clipData);
}
}
}
});
JPanel p = new JPanel();
p.add(copy);
p.add(clear);
p.add(paste);
contentPane.add(p, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.show();
}
}
class ImageSelection extends TransferHandler implements Transferable {
private static final DataFlavor flavors[] = { DataFlavor.imageFlavor };
private JLabel source;
private Image image;
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
public boolean canImport(JComponent comp, DataFlavor flavor[]) {
if (!(comp instanceof JLabel)) {
return false;
}
for (int i = 0, n = flavor.length; i < n; i++) {
for (int j = 0, m = flavors.length; j < m; j++) {
if (flavor[i].equals(flavors[j])) {
return true;
}
}
}
return false;
}
public Transferable createTransferable(JComponent comp) {
// Clear
source = null;
image = null;
if (comp instanceof JLabel) {
JLabel label = (JLabel) comp;
Icon icon = label.getIcon();
if (icon instanceof ImageIcon) {
image = ((ImageIcon) icon).getImage();
source = label;
return this;
}
}
return null;
}
public boolean importData(JComponent comp, Transferable t) {
if (comp instanceof JLabel) {
JLabel label = (JLabel) comp;
if (t.isDataFlavorSupported(flavors[0])) {
try {
image = (Image) t.getTransferData(flavors[0]);
ImageIcon icon = new ImageIcon(image);
label.setIcon(icon);
return true;
} catch (UnsupportedFlavorException ignored) {
} catch (IOException ignored) {
}
}
}
return false;
}
// Transferable
public Object getTransferData(DataFlavor flavor) {
if (isDataFlavorSupported(flavor)) {
return image;
}
return null;
}
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(DataFlavor.imageFlavor);
}
}
Setting an image on the clipboard with a custom Transferable object to hold the image
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import javax.swing.ImageIcon;
public class Main {
public static void main(String[] argv) throws Exception {
ImageSelection imgSel = new ImageSelection(new ImageIcon("a.png").getImage());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);
}
}
class ImageSelection implements Transferable {
private Image image;
public ImageSelection(Image image) {
this.image = image;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (!DataFlavor.imageFlavor.equals(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return image;
}
}
Taken from the Sun documentation on Clipboard API
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.awt.Button;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextArea;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/** Taken from the Sun documentation on Clipboard API */
public class ClipboardTest extends Frame implements ClipboardOwner,
ActionListener {
TextArea srcText, dstText;
Button copyButton, pasteButton;
Clipboard clipboard = getToolkit().getSystemClipboard();
public ClipboardTest() {
super("Clipboard Test");
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);
srcText = new TextArea(8, 32);
c.gridwidth = 2;
c.anchor = GridBagConstraints.CENTER;
gridbag.setConstraints(srcText, c);
add(srcText);
copyButton = new Button("Copy Above");
copyButton.setActionCommand("copy");
copyButton.addActionListener(this);
c.gridy = 1;
c.gridwidth = 1;
gridbag.setConstraints(copyButton, c);
add(copyButton);
pasteButton = new Button("Paste Below");
pasteButton.setActionCommand("paste");
pasteButton.addActionListener(this);
pasteButton.setEnabled(false);
c.gridx = 1;
gridbag.setConstraints(pasteButton, c);
add(pasteButton);
dstText = new TextArea(8, 32);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
gridbag.setConstraints(dstText, c);
add(dstText);
pack();
}
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if (cmd.equals("copy")) {
// Implement Copy operation
String srcData = srcText.getText();
if (srcData != null) {
StringSelection contents = new StringSelection(srcData);
clipboard.setContents(contents, this);
pasteButton.setEnabled(true);
}
} else if (cmd.equals("paste")) {
// Implement Paste operation
Transferable content = clipboard.getContents(this);
if (content != null) {
try {
String dstData = (String) content
.getTransferData(DataFlavor.stringFlavor);
dstText.append(dstData);
} catch (Exception e) {
System.out
.println("Couldn"t get contents in format: "
+ DataFlavor.stringFlavor
.getHumanPresentableName());
}
}
}
}
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("Clipboard contents replaced");
}
public static void main(String[] args) {
ClipboardTest test = new ClipboardTest();
test.setVisible(true);
}
}
Using the clipboard
// : c14:CutAndPaste.java
// Using the clipboard.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
public class CutAndPaste extends JFrame {
private JMenuBar mb = new JMenuBar();
private JMenu edit = new JMenu("Edit");
private JMenuItem cut = new JMenuItem("Cut"), copy = new JMenuItem("Copy"),
paste = new JMenuItem("Paste");
private JTextArea text = new JTextArea(20, 20);
private Clipboard clipbd = getToolkit().getSystemClipboard();
public CutAndPaste() {
cut.addActionListener(new CutL());
copy.addActionListener(new CopyL());
paste.addActionListener(new PasteL());
edit.add(cut);
edit.add(copy);
edit.add(paste);
mb.add(edit);
setJMenuBar(mb);
getContentPane().add(text);
}
class CopyL implements ActionListener {
public void actionPerformed(ActionEvent e) {
String selection = text.getSelectedText();
if (selection == null)
return;
StringSelection clipString = new StringSelection(selection);
clipbd.setContents(clipString, clipString);
}
}
class CutL implements ActionListener {
public void actionPerformed(ActionEvent e) {
String selection = text.getSelectedText();
if (selection == null)
return;
StringSelection clipString = new StringSelection(selection);
clipbd.setContents(clipString, clipString);
text.replaceRange("", text.getSelectionStart(), text
.getSelectionEnd());
}
}
class PasteL implements ActionListener {
public void actionPerformed(ActionEvent e) {
Transferable clipData = clipbd.getContents(CutAndPaste.this);
try {
String clipString = (String) clipData
.getTransferData(DataFlavor.stringFlavor);
text.replaceRange(clipString, text.getSelectionStart(), text
.getSelectionEnd());
} catch (Exception ex) {
System.err.println("Not String flavor");
}
}
}
public static void main(String[] args) {
run(new CutAndPaste(), 300, 200);
}
public static void run(JFrame frame, int width, int height) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
} ///:~
Write a string to the system clipboard
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
public class Main {
public static void main(String[] argv) throws Exception {
StringSelection ss = new StringSelection("str");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}
}