在你的JTextComponent组件中加入Undo、Redo功能

1/5/2008来源:Java教程人气:6421


  费话就不说了,且看看我是如何实现的。

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();
}
}