在Eclipse文本编辑器中创建工具栏

时间:2012-04-17 06:52:35

标签: java eclipse eclipse-plugin

我有一个Eclipse插件,其中我需要在文本编辑器中使用工具栏,就像切换面包屑视图一样。 Eclipse中是否有允许我这样做的通用实用程序类?

@Override
protected ISourceViewer createSourceViewer(Composite parent,
                                           IVerticalRuler ruler, 
                                           int styles)
{
    composite = new Composite(parent, SWT.NONE);
    GridLayout gridLayout = new GridLayout(1, true);
    gridLayout.numColumns = 1;
    gridLayout.marginHeight = 0;
    gridLayout.marginWidth = 0;
    composite.setLayout(gridLayout);

    ToolBar toolBar = new ToolBar(composite, SWT.FLAT);
    GridData gridData = new GridData(GridData.FILL, SWT.TOP, true, false);
    toolBar.setLayoutData(gridData);
    toolBarManager = new ToolBarManager(toolBar);

    return super.createSourceViewer(composite, ruler, styles);
}

2 个答案:

答案 0 :(得分:1)

假设您有基于org.eclipse.ui.editors.text.TextEditor类的文本编辑器,则必须覆盖AbstractDecoratedTextEditor.createSourceViewer(Composite parent, ...)。基本上

  • 使用Compositeparent中创建新的顶级GridLayout(1, false)。 (由于Composite参数中的parentFillLayout),因此需要这样做。
  • 使用ToolBarManager创建GridData(FILL, TOP, true, false)并执行'mng.createControl(top)'。
  • 使用Composite创建新的孩子GridData(FILL, FILL, true, true)
  • 调用super.createSourceViewer(child, ...)

答案 1 :(得分:1)

托尼的回答很好,但有时候却是 super.createSourceViewer(composite, ruler, styles);
将改变父母的布局,正如RTA在Tony的回答中评论的那样,真正的编辑区域将会丢失 当我想做与RTA完全相同的事情时,我遇到了这个问题 这是我的解决方案:

@Override
protected ISourceViewer createSourceViewer(Composite parent,
        IVerticalRuler ruler, int styles) {
    changeParentLayout(parent);
    Label label = createPathLabel(parent);
    ISourceViewer viewer = super.createSourceViewer(parent, ruler, styles);
    updateSourceViewerLayout(parent, label);
    return viewer;
}

//change the parent layout to grid layout,
//so that the source file area can be shown
protected void changeParentLayout(Composite parent) {
    parent.setLayout(new GridLayout(1, false));
}

//i need a label here, ToolBar will be the same
protected Label createPathLabel(Composite parent) {
    Label lblNewLabel = new Label(parent, SWT.NONE);
    lblNewLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false, 1, 1));
    lblNewLabel.setText(getFilePath());
    return lblNewLabel;
}

//after adding the label i need and call super.createSourceViewer()
//now all widgets are ready, we need to change the editor area's layout data to grid data
//here if you only have two widgets: label and area, you can directly choose the edit area widget. i used a loop to find all sub widgets
protected void updateSourceViewerLayout(Composite parent, Label label) {
    Control[] children = parent.getChildren();
    if (children.length < 2) return;
    for (Control child : children) {
        if (child != label) {
            child.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        }
    }
}

private String getFilePath() {
    //get the path I want
    return "";
}