为ToolBarManager添加自定义控件

来源:互联网 发布:今日头条 h5 源码 php 编辑:程序博客网 时间:2024/05/11 22:38
       项目要实现在Editor的ToolBarManager添加Combo控件的需求。在www.java2s.com上查了一下,没有发现其有现成的例子。而且觉得这个网站的例子大多关注的是SWT的使用,对JFace这一层面关注不多。但是放着JFace不用,直接用SWT的话,开发效率不高,而且容易出现自己引发的错误。看了一下JFace的源码,研究了以下的实现方法。
       ToolBarManager是对SWT的ToolBar控件的封装,只用它可以省去这些底层控件的关注。就像使用了TableViewer,就不需要再去关心TableItem这些繁琐的细节一样。
       一般我们都是向ToolBarManager里面添加Action,显示的效果就是一个Button.如果希望显示一个Combo或者Text这样的控件,就不能向其中添加Action了。而且又不想使用ToolBar处理具体的ToolItem。只要构建自己的ControlContribution 就可以很容易的实现这样的功能。
       首先要继承ControlContribution类,实现其protected Control createControl(Composite parent)方法,在这个方法中构建自己希望的控件。只要是Control的子类就都可以。然后将其添加到ToolBarManager里面即可。
       程序如下:
    ·  
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ControlContribution;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

class ComboContribution extends ControlContribution {

    
public ComboContribution(String id) {
        
super(id);
    }


    @Override
    
protected Control createControl(Composite parent) {
        Combo combo 
= new Combo(parent, SWT.NONE);
        combo.setItems(
new String[] "Jurassic Park""E.T.""JAW" });
        
return combo;
    }

}


public class TestToolBar {

    
public TestToolBar(Shell shell) {
        IAction runAction 
= new Action("Run"{

            
public void run() {

            }

        }
;

        ToolBarManager barManager 
= new ToolBarManager(SWT.NONE);
        barManager.add(runAction);

        ComboContribution combo 
= new ComboContribution("Combo.contribution");
        barManager.add(combo);

        barManager.createControl(shell);

        GridData gd 
= new GridData(GridData.FILL_HORIZONTAL);
        barManager.getControl().setLayoutData(gd);
    }


    
/**
     * DOC qianbing Comment method "main".
     * 
     * 
@param args
     
*/

    
public static void main(String[] args) {
        Display display 
= new Display();

        
final Shell shell = new Shell(display);
        shell.setLayout(
new GridLayout());

        
new TestToolBar(shell);

        shell.setSize(
300300);
        shell.open();
        
while (!shell.isDisposed()) {
            
if (!display.readAndDispatch())
                display.sleep();
        }

        display.dispose();
    }

}


    其中barManager.createControl(shell);是构建ToolBar,如果在ToolBarManager的构造方法中已经传入,此行即可省略。


原创粉丝点击