你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Java专栏
使用Java来实现编辑器的Undo Redo功能(1)
 

用java实现编辑器的Undo Redo功能,非常的方便,下面是一个实现这个功能的类,import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JEditorPane;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.JTextComponent;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
/**
* UndoWrapper is responsible for adding undo and redo support to text components.
* @author Antonio Vieiro (antonio@antonioshome.net), $Author: $
* @version $Revision: $
*/
public class UndoWrapper
 implements UndoableEditListener
{
 private UndoManager undoManager;
 private UndoAction undoAction;
 private RedoAction redoAction;
 private JEditorPane textComponent;
  
 /**
  * Creates a new instance of UndoWrapper
  */
 public UndoWrapper( JEditorPane aComponent )
 {
  textComponent = aComponent;
  undoManager = new UndoManager();
  undoAction = new UndoAction();
  redoAction = new RedoAction();
  textComponent.getDocument().addUndoableEditListener( this );
  textComponent.getInputMap().put( (KeyStroke) undoAction.getValue(
Action.ACCELERATOR_KEY), "undo" );
  textComponent.getInputMap().put( (KeyStroke) redoAction.getValue(
Action.ACCELERATOR_KEY), "redo" );
  textComponent.getActionMap().put( "undo", undoAction );
  textComponent.getActionMap().put( "redo", redoAction );
 }
 
 public void undoableEditHappened(UndoableEditEvent e)
 {
  undoManager.addEdit( e.getEdit() );
  undoAction.updateUndoState();
  redoAction.updateRedoState();
 }
 
 /**
  * UndoAction is the Action responsible for handling the undo operation.
  */
 class UndoAction
  extends AbstractAction
 {
  public UndoAction()
  {
   super( "Cannot undo" ); // TODO: I18N
   setEnabled( false );
   putValue( Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl Z") );
  }
  
  public void actionPerformed(ActionEvent e)
  {
   try
   {
    undoManager.undo();
   }
   catch( CannotUndoException cue )
   {
    // TODO: Use logging?
    cue.printStackTrace( System.err );
   }
  
(编辑:aniston)

  推荐精品文章

·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录
·2023年10月目录
·2023年9月目录 
·2023年8月目录 
·2023年7月目录
·2023年6月目录 
·2023年5月目录
·2023年4月目录 
·2023年3月目录 
·2023年2月目录 
·2023年1月目录 

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089