费话就不说了,且看看我是如何实现的。
package lookbook.swing;
import Javax.swing.undo.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author lookbook
* @version 1.0
*/
public class UndoFrame extends JFrame{
JPanel jPanel1 = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JScrollPane jScrollPane1 = new JScrollPane();
JTextArea undoTextArea = new JTextArea();
public UndoFrame() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
jPanel1.setLayout(borderLayout1);
undoTextArea.setText("");
this.setUndo(undoTextArea);
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.add(jScrollPane1, BorderLayout.CENTER);
jScrollPane1.getViewport().add(undoTextArea, null);
}
//设置Undo、Redo功能的函数
private void setUndo(JTextComponent textComponent){
final UndoManager undo = new UndoManager();
Document doc = textComponent.getDocument();
doc.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textComponent.getActionMap().put("Undo",
new AbstractAction("Undo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canUndo()) {
undo.undo();
}
} catch (CannotUndoException e) {
}
}
});
textComponent.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textComponent.getActionMap().put("Redo",
new AbstractAction("Redo") {
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canRedo()) {
undo.redo();
}
} catch (CannotRedoException e) {
}
}
});
textComponent.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
}
public static void main(String[] args) {
UndoFrame undo = new UndoFrame();
undo.setSize(200,200);
undo.show();
}
}