首页 > 学院 > 开发设计 > 正文

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

2019-11-18 15:23:06
字体:
来源:转载
供稿:网友

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

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表