import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
public class Test50 extends Frame implements ActionListener{
MenuBar menubar;Menu menu;
MenuItem copy,cut,paste;
TextArea text1,text2;
Clipboard clipboard = null;
Test50(){
clipboard = getToolkit().getSystemClipboard();//获取系统剪贴板
menubar = new MenuBar();
menu = new Menu("Edit");
copy = new MenuItem("copy");
cut = new MenuItem("cut");
paste = new MenuItem("paste");
text1 = new TextArea(20,20);
text2 = new TextArea(20,20);
copy.addActionListener(this);
cut.addActionListener(this);
paste.addActionListener(this);
setLayout(new FlowLayout());
menubar.add(menu);
menu.add(copy);menu.add(cut);menu.add(paste);
setMenuBar(menubar);
add(text1);add(text2);
setBounds(100,100,200,300);
setVisible(true);pack();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==copy){//复制到剪贴板
String temp = text1.getSelectedText();//拖动鼠标选取文本文件
StringSelection text = new StringSelection(temp);
clipboard.setContents(text,null);
}
else if(e.getSource()==cut){
String temp = text1.getSelectedText();
StringSelection text = new StringSelection(temp);
clipboard.setContents(text,null);
int start = text1.getSelectionStart();
int end = text1.getSelectionEnd();
text1.replaceRange("",start,end);//从Text1中删除被选的文
}
else if(e.getSource()==paste){//从剪贴板粘贴数据
Transferable contents = clipboard.getContents(this);
DataFlavor flavor = DataFlavor.stringFlavor;
if(contents.isDataFlavorSupported(flavor))
try{
String str;
str = (String)contents.getTransferData(flavor);
text2.append(str);
}catch(Exception ee){}
}
}
public static void main(String args[]){
Test50 win = new Test50();
}
}