如何在JAVA中实现撤销,剪切,复制,粘贴4大功
1个回答
2017-09-16
展开全部
要用到java.awt.datatransfer包中的Clipboard类importjava.awt.*;importjava.awt.event.*;importjava.awt.datatransfer.*;publicclassTestextendsFrameimplementsActionListener{MenuBarmenubar;Menumenu;MenuItemcopy,cut,paste;TextAreatext1,text2;Clipboardclipboard=null;Test(){clipboard=getToolkit().getSystemClipboard();//获取系统剪贴板。menubar=newMenuBar();menu=newMenu("Edit");copy=newMenuItem("copy");cut=newMenuItem("cut");paste=newMenuItem("paste");text1=newTextArea(20,20);text2=newTextArea(20,20);copy.addActionListener(this);cut.addActionListener(this);paste.addActionListener(this);setLayout(newFlowLayout());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(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){System.exit(0);}});}publicvoidactionPerformed(ActionEvente){if(e.getSource()==copy)//拷贝到剪贴板。{Stringtemp=text1.getSelectedText();//拖动鼠标选取文本。StringSelectiontext=newStringSelection(temp);clipboard.setContents(text,null);}elseif(e.getSource()==cut)//剪贴到剪贴板。{Stringtemp=text1.getSelectedText();//拖动鼠标选取文本。StringSelectiontext=newStringSelection(temp);clipboard.setContents(text,null);intstart=text1.getSelectionStart();intend=text1.getSelectionEnd();text1.replaceRange("",start,end);//从Text1中删除被选取的文本。}elseif(e.getSource()==paste)//从剪贴板粘贴数据。{Transferablecontents=clipboard.getContents(this);DataFlavorflavor=DataFlavor.stringFlavor;if(contents.isDataFlavorSupported(flavor))try{Stringstr;str=(String)contents.getTransferData(flavor);text2.append(str);}catch(Exceptionee){}}}publicstaticvoidmain(Stringargs[]){Testwin=newTest();}}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询