package clipborad;
import javaxswingJTextArea;
import javaawtdatatransfer*;
import javaawt*;
import javaxswing*;
import javaio*;
import javaxswingundo*;
import javaxswingtext*;
import javaxswingevent*;
import javaawtevent*;
/**
* Title: 用JAVA实现UndoRedoCopyPasteCut
* Description:用JAVA实现UndoRedoCopyPasteCut
* Copyright: Copyright (c)
* Company:
* @author: 彭建雄
* @version
*/
public class ClipTextArea extends JTextArea implements ClipboardOwner{
Clipboard strBoard = thisgetToolkit()getSystemClipboard();
UndoManager undo = new UndoManager();
Document doc = getDocument();
public ClipTextArea() {
docaddUndoableEditListener(new UndoableEditListener(){
public void undoableEditHappened(UndoableEditEvent e) {
doc_addedit(e);}
});
addActionMap();
}
public void addActionMap()
{
getActionMap()put(Undo new AbstractAction(Undo) {
public void actionPerformed(ActionEvent evt) {
try {
if (undocanUndo()) {
undoundo();
}
} catch (CannotUndoException e) {
}
}
});
getInputMap()put(KeyStrokegetKeyStroke(control Z) Undo);
getActionMap()put(Redonew AbstractAction(Redo) {
public void actionPerformed(ActionEvent evt) {
try
{
if (undocanRedo()) {
undoredo();
}
} catch (CannotRedoException e) {
}
}
});
getInputMap()put(KeyStrokegetKeyStroke(control R) Redo);
getActionMap()put(Copynew AbstractAction(Copy) {
public void actionPerformed(ActionEvent evt) {
copy();
}
});
getInputMap()put(KeyStrokegetKeyStroke(control C) Copy);
getActionMap()put(Cutnew AbstractAction(Cut) {
public void actionPerformed(ActionEvent evt) {
cut();
}
});
getInputMap()put(KeyStrokegetKeyStroke(control X) Cut);
getActionMap()put(Pastenew AbstractAction(Paste) {
public void actionPerformed(ActionEvent evt) {
paste();
}
});
getInputMap()put(KeyStrokegetKeyStroke(control V) Paste);
}
public void copy()
{
String sCopy = getSelectedText();
if (sCopy != null)
{
StringSelection sSelection = new StringSelection(sCopy);
strBoardsetContents(sSelectionthis);
}
}
public void cut()
{
String sCopy = getSelectedText();
if (sCopy != null)
{
StringSelection sSelection = new StringSelection(sCopy);
strBoardsetContents(sSelectionthis);
thisreplaceSelection();
}
}
public void paste()
{
Transferable sTransf = strBoardgetContents(this);
if (sTransf!=null)
{
try
{
String sPaste = (String)sTransfgetTransferData(DataFlavorstringFlavor);
thisreplaceRange(sPastegetSelectionStart()getSelectionEnd());
}
catch(UnsupportedFlavorException e)
{
}
catch(IOException ioe)
{
}
}
}
public void lostOwnership(Clipboard clipboardTransferable contents)
{
}
void doc_addedit(UndoableEditEvent e)
{
undoaddEdit(egetEdit());
}
}