java复制粘贴剪切方法代码_在JAVA中实现撤销,剪切,复制,粘贴4大功能

要用到java.awt.datatransfer包中的Clipboard类

import   java.awt.*;import   java.awt.event.*;

import   java.awt.datatransfer.*;

public   class   Test   extends   Frame   implements   ActionListener

{     MenuBar   menubar;   Menu   menu;

MenuItem   copy,cut,paste;

TextArea   text1,text2;

Clipboard   clipboard=null;

Test()

{     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,250);   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[])

{     Test   win=new   Test();

}

}

转自:http://topic.csdn.net/t/20050101/16/3693365.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值