在你的JTextComponent组件中加入Undo、Redo功能
2008-01-05 08:34:38 来源:WEB开发网核心提示:费话就不说了,且看看我是如何实现的,在你的JTextComponent组件中加入Undo、Redo功能,package lookbook.swing;import javax.swing.undo.*;import javax.swing.*;import javax.swing.text.*;import javax
费话就不说了,且看看我是如何实现的。
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();
}
}
Tags:JTextComponent 组件 加入
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接