动态更改Eclipse工具栏图标

4

我有一个带有自己图标的工具栏项目,它在plugin.xml文件中定义如下:

<action
class="MyActionClass"
id="MyActionID"
label="MyActionLabel"
menubarPath="MyActionMenuBarPath"
toolbarPath="MyActionToolBarPath"
icon="icon/myicon.png" <---- this one
     ...
</action>

如何在需要时动态更改这个?我是指从代码中更改它。
2个回答

5
请使用 org.eclipse.ui.menus 扩展点,并添加 menuContribution 以实现动态效果。 dynamicclass 应继承 ControlContribution 并实现 createControl 方法以创建一个按钮。

3

您需要在您的Handler类中实现IElementUpdater接口。
请参考:https://dev59.com/7H_aa4cB1Zd3GeqP5JVf#23742598

  1. Handler class

    import java.util.Map;    
    import org.eclipse.core.commands.AbstractHandler;
    import org.eclipse.core.commands.ExecutionEvent;
    import org.eclipse.core.commands.ExecutionException;
    import org.eclipse.jface.resource.ImageDescriptor;
    import org.eclipse.ui.commands.IElementUpdater;
    import org.eclipse.ui.menus.UIElement;    
    import com.packpub.e4.menu.Activator;     
    public class SampleHandler2 extends 
                 AbstractHandler implements IElementUpdater{       
        private static ImageDescriptor image_enable = 
            Activator.getImageDescriptor("icons/btn_adapt_enable.png");
        private static ImageDescriptor image_disable = 
            Activator.getImageDescriptor("icons/btn_adapt_disable.png");        
        /**
         * The constructor.
         */
        public SampleHandler2() {
    
        }    
        /**
         * the command has been executed, so extract extract the needed information
         * from the application context.
         */
        public Object execute(ExecutionEvent event) throws ExecutionException {
            //...
            return null;
        }    
        @Override
        public void updateElement(UIElement element, @SuppressWarnings("rawtypes") Map map) {
            boolean condition = false;            
            //...            
            if( condition ) { 
                element.setIcon(image_disable);
            }else{
                element.setIcon(image_enable);
            }        
        }
    }
    
  2. invoke this Handler using ICommandService:

        IWorkbenchWindow window = part.getSite().getWorkbenchWindow();
        ICommandService commandService = (ICommandService) window.getService(ICommandService.class);
        if (commandService != null) {
            commandService.refreshElements("com.packpub.e4.menu.commands.sampleCommand", null);
        }
    
感谢您的选择。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接