服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

在你的jtextcomponent组件中加入undo、redo功能


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

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

扫描关注微信公众号