如何为sourceviewer使用undomanager

时间:2014-10-24 16:33:18

标签: java eclipse-plugin

我需要在源查看器中添加undo redo功能。以下是我的代码。

public class MyViewer extends SourceViewer {
    public MyViewer(final Composite parent, final int styles) {
        super(parent, null, styles);

        final Font font = JFaceResources.getFont(MyConstants.EDITOR_TEXT_FONT);
        getTextWidget().setFont(font);
        IUndoManager undoManager = getUndoManager(); //new TextViewerUndoManager(25);
        //setUndoManager(undoManager); //new TextViewerUndoManager(10));
        //undoManager.connect(this);
        if (undoManager != null) {
            undoManager.reset();
        } else {
            undoManager = new TextViewerUndoManager(25);
            setUndoManager(undoManager);
            undoManager.connect(this);
        }
    }

    @Override
    public void setDocument(final IDocument document) {
    ...
    }

    @Override
    public void setHyperlinkPresenter(final IHyperlinkPresenter hyperlinkPresenter) throws IllegalStateException {
    ...
    }

}

我添加了一个键绑定,如下图所示。

enter image description here

仍然撤消重做不起作用。 我不确定密钥绑定是错误的还是我错过了我的代码中的内容或两者。请突出我的错误。

1 个答案:

答案 0 :(得分:0)

我从here

找到了以下代码
viewer.getTextWidget().addKeyListener(new KeyListener() {
 @Override
  public void keyReleased(KeyEvent e) {
       // TODO Auto-generated method stub
  }

 @Override
 public void keyPressed(KeyEvent e) {
   if( isUndoKeyPress( e )){
     viewer.doOperation(ITextOperationTarget.UNDO);
   }  else if( isRedoKeyPress( e )) {
      viewer.doOperation(ITextOperationTarget.REDO);
   }
 }

  private boolean isRedoKeyPress(KeyEvent e) {
     return (( e.stateMask & SWT.CONTROL ) > 0) && ((e.keyCode =='y' ) (e.keyCode == 'Y'));
   }

   private boolean isUndoKeyPress(KeyEvent e) {
          return (( e.stateMask & SWT.CONTROL) > 0 ) && ((e.keyCode == 'z' ) (e.keyCode =='Z'));
   }
});

添加此代码后,我能够进行撤消和重做工作。看起来我不需要在首选项页面中完成的附加键绑定。现在,首选项页面如下所示

enter image description here