JAVA的剪切板

java的剪切板相关的操作相关的类和接口都放在了java.awt.datatransfer包下。下面是一个有关复制和粘帖的程序:
import java.awt.Frame;
import java.awt.BorderLayout;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.DataFlavor;
import java.awt.Toolkit;
import java.awt.TextArea;
import java.awt.Button;
import java.awt.Panel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
public class SimpleClipboard 
{
	private Frame f=new Frame("simple_clipboard");
	//get system clipboard
	private Clipboard clipboard=Toolkit.getDefaultToolkit().getSystemClipboard();
	private TextArea jtaCopyTo=new TextArea(5,20);
	private TextArea jtaPaste=new TextArea(5,20);
	private Button btCopy=new Button("copy");
	private Button btPaste=new Button("Paste");
	public void init(){
		Panel p=new Panel();
		p.add(btCopy);
		p.add(btPaste);
		btCopy.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				//将多行的字符串封装成StringSelection对象
				StringSelection contents=new StringSelection(jtaCopyTo.getText());
				clipboard.setContents(contents,null);
			}
		});
		btPaste.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				//判读剪切板中是否有东西
				if(clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)){
					try{
						//取出内容
						String content=(String)clipboard.getData(DataFlavor.stringFlavor);
						jtaPaste.append(content);
					}
					catch(Exception e2){
						e2.printStackTrace();
					}
				}
			}
		});
		//创建一个水平放置的BOX
		Box box=new Box(BoxLayout.X_AXIS);
		box.add(jtaCopyTo);
		box.add(jtaPaste);
		f.add(p,BorderLayout.SOUTH);
		f.add(box,BorderLayout.CENTER);
		f.pack();
		f.setVisible(true);
	}
	public static void main(String[] args) 
	{
		new SimpleClipboard().init();
	}
}
如果需要获取本地剪切板:Clipboard clipboard=new Clipboard("cb");

你可能感兴趣的:(javaSE基础学习)