Eclipse的Command应用教程(二)

Eclipse Advanced Commands

This article describes use cases for Eclipse commands which go beyond the simple one for adding commands to menus, toolbars, etc.

This article is based on Eclipse Indigo (3.7).


1. Eclipse Commands

For an introduction into Eclipse Commands please see Eclipse Commands Tutorial .

2.  Enabled when (visible when)

The command framework allows to restrict the availability and visibility of commands, handlers and ui contributions via the core expressions .

In this example we want the command only be enabled if one item from a list of items is selected.

Create a new project "de.vogella.rcp.commands.enable" based on the "RCP application with a view" example.

Add a command with the ID "de.vogella.rcp.commands.enable.command". Add this command to the menu and the toolbar and create the following default handler.

 

			
package de.vogella.rcp.commands.enable.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.handlers.HandlerUtil;

public class Command extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		MessageDialog.openInformation(HandlerUtil.getActiveWorkbenchWindow(
				event).getShell(), "Info", "Info for you");

		return null;
	}

}

		

 

Select plugin.xml and add "org.eclipse.core.expressions" as a dependency. Select then the Extensions tab and add the extensions org.eclipse.core.expressions.definitions.

Using right mouse click add a definition "oneElementSelected". Add a "with" variable "selection".

 

Tip

"selection" is a predefined variable which will be calculated automatically by Eclipse. See core expressions for additional variables you can use. For example for a popup menu "activeMenuSelection" provides the selection.

 

On the "activeMenuSelection" right mouse click and add a count with the value "1". The result should look like

 

 

On your handler, right mouse click and select enabledWhen. Right mouse click and add a "reference" to it with the value "oneElementSelected". The result should look like.

 

 

The expression were are using is based on "selection". Therefore the list must register itself as selection provider to inform the workbench in case something is selected. Therefore add "getSite().setSelectionProvider(viewer);" in createPartControl of View.java.

 

			
public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
				| SWT.V_SCROLL);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(getViewSite());
		// Makes the selection available to the workbench
		getSite().setSelectionProvider(viewer);
	}
	
		

 

If you now run the application your command should only be enabled if one element in the list is selected.

 

Tip

You can also only display the menu if one item is selected. The approach is the same but you only define the restriction on the menu contribution directly (visible when on the command in the menu). For a command in the toolbar the definition would look like:

 

 

 

<script type="text/javascript"></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

3. Eclipse standard commands

3.1. Overview

Eclipse provides lots of standard commands which you can re-use. Just press on the "Browse button" while defining your commandId to see the available standard commands. For example the screenshot shows the usage of the standard about dialog command.

The advantage of using standard commands is that you get the keybinding, icons, etc for free.

 

 

 

Tip

Standard commands sometimes map to actions which are contributed via ActionFactory in the class ApplicationActionBarAdvisor. If the ActionFactory returns an IAction you need to register this action. If not these commands are inactive in your menu. For example the following made the reset perspective and welcome command active.

 

 

				
// Method belongs to class ApplicationActionBarAdvisor
	@Override
	protected void makeActions(IWorkbenchWindow window)
	{
		IWorkbenchAction quickStartAction = ActionFactory.INTRO.create(window);
		register(quickStartAction);
		IWorkbenchAction resetView = ActionFactory.RESET_PERSPECTIVE
				.create(window);
		register(resetView);
	}
			

 

3.2. Example

You can also use standard command and define a new handler for this command, e.g. you can use the standard Eclipse delete command (org.eclipse.ui.edit.delete).

 

Tip

To find the id of existing commands you can you the Eclipse Plugin Spy.

 

You can use the extension point "org.eclipse.ui.handlers" to define new handlers for the standard commands.

 

Tip

Eclipse requires you to have only one active handler at the time therefore you have to use the "activeWhen" restriction on the handler to make it more special then the standard binding. To use for example delete in several views with different handlers use "activeWhen" with the variable "activePartId" and as the value your view id.

 

Create a new RCP application "de.vogella.rcp.commands.standardcommands" with the template "Hello RCP".

Create a handler for the command "org.eclipse.ui.edit.delete" which display a message box. Add the command "org.eclipse.ui.edit.delete" to the menu.

 

 

 

 

The result should look like the following.

 

 

4. Calling commands directly via code

You can call a command directly. For example if you have a command "add.command" defined you can call it via the following coding.

 

			

// From a view you get the site which allow to get the service
IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class);
try {
	handlerService.executeCommand("add.command", null);
	} catch (Exception ex) {
		throw new RuntimeException("add.command not found");
		// Give message
		}
}

		

 

This coding above is called within a view which provides access to the site and to services. You can also get the service via the WorkbenchWindow.

5. Providing your own expression

You can write your own Java class which can be used define a variable which can then be used to define if a certain UI element shall be active or not. For example you can read the authorization of the user from your own class and then return the value which is assign to the user. This return value can then be used in a visible / enabled statement. This is similar to the usage of the core expressions we have seen earlier.

Create a RCP application "de.vogella.rcp.commands.sourceprovider" with the template "Hello RCP".

We will create a source provider. This source provider can provide variables which can be used in defining the visibility of commands. Add the extension point "org.eclipse.ui.services" to your plugin and create a new service provider.

 

 

 

 

This defines a service which provides the variable "de.vogella.rcp.commands.sourceprovider.active" to the workbench. This class must implement ISourceProvider. This value can then be used similar to a core expression. Maintain the following code.

 

			
package de.vogella.rcp.commands.sourceprovider;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.ui.AbstractSourceProvider;
import org.eclipse.ui.ISources;

public class CommandState extends AbstractSourceProvider {
	public final static String MY_STATE = "de.vogella.rcp.commands.sourceprovider.active";
	public final static String ENABLED = "ENABLED";
	public final static String DISENABLED = "DISENABLED";
	private boolean enabled = true;


	@Override
	public void dispose() {
	}

	// We could return several values but for this example one value is sufficient
	@Override
	public String[] getProvidedSourceNames() {
		return new String[] { MY_STATE };
	}
	
	// You cannot return NULL
	@SuppressWarnings("unchecked")
	@Override
	public Map getCurrentState() {
		Map map = new HashMap(1);
		String value = enabled ? ENABLED : DISENABLED;
		map.put(MY_STATE, value);
		return map;
	}

	

	// This method can be used from other commands to change the state
	// Most likely you would use a setter to define directly the state and not use this toogle method
	// But hey, this works well for my example
	public void toogleEnabled() {
		enabled = !enabled ;
		String value = enabled ? ENABLED : DISENABLED;
		fireSourceChanged(ISources.WORKBENCH, MY_STATE, value);
	}

}

		

 

Create two commands "de.vogella.rcp.commands.sourceprovider.command1" and "de.vogella.rcp.commands.sourceprovider.command2". Create any handler you want for the first command. Command2 will be used to change the state in our ISourceProvider. Maintain the following code for the handler.

 

			
package de.vogella.rcp.commands.sourceprovider.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.services.ISourceProviderService;

import de.vogella.rcp.commands.sourceprovider.CommandState;

public class Command2 extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// Get the source provider service
		ISourceProviderService sourceProviderService = (ISourceProviderService) HandlerUtil
				.getActiveWorkbenchWindow(event).getService(
						ISourceProviderService.class);
		// Now get my service
		CommandState commandStateService = (CommandState) sourceProviderService
				.getSourceProvider(CommandState.MY_STATE);
		commandStateService.toogleEnabled();
		return null;
	}

}

		

 

Add both commands to the menu.

Now use the state provided by your ISourceProvider in your declaration of your menu.

 

 

This looks in plugin.xml like the following.

 

			
<extension
         point="org.eclipse.ui.menus">
      <menuContribution
            locationURI="menu:org.eclipse.ui.main.menu">
         <command
               commandId="de.vogella.rcp.commands.sourceprovider.command1"
               label="Command1"
               style="push">
            <visibleWhen
                  checkEnabled="false">
               <with
                     variable="de.vogella.rcp.commands.sourceprovider.active">
                  <equals
                        value="ENABLED">
                  </equals>
               </with>
            </visibleWhen>
         </command>
         <command
               commandId="de.vogella.rcp.commands.sourceprovider.command2"
               label="Command2"
               style="push">
         </command>
      </menuContribution>
</extension>
		

 

If you now start your application can select the second command the first command will not be available anymore. If you press it again the first command will be displayed again.

6. Using parameters in commands

You can also define parameters in commands. Create project "de.vogella.rcp.commands.parameterfirst" using the "Hello RCP" template.

Create a command with the id "de.vogella.rcp.commands.parameterfirst.helloName" and a default handler "de.vogella.rcp.commands.parameterfirst.handler.HelloName".

Right click on your command, select New -> commandParameter

 

 

Use the following id for the parameter "de.vogella.rcp.commands.parameterfirst.commandParameter1"

 

 

In the handler you have to evaluate the parameter.

 

			
package de.vogella.rcp.commands.parameterfirst.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.handlers.HandlerUtil;

public class HelloName extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String name = event
				.getParameter("de.vogella.rcp.commands.parameterfirst.commandParameter1");
		MessageDialog.openInformation(HandlerUtil.getActiveShell(event),
				"Hello", "Hello " + name);
		return null;
	}
}

		

 

Add this command to the menu. On the command, right click and select New -> Parameter

 

 

As name maintain the name of the parameter, pass as value the value you want to use in your handler.

 

 

Add the same command again to the menu and pass another parameter.

If you run your application and select the menu entry the value should be used in the message box.

7. Defining commands at runtime

You can create commands at runtime. Create project "de.vogella.rcp.commands.runtimecommands" using the "Hello RCP" template.

Define a menu contribution. Maintain the class "de.vogella.rcp.commands.runtimecommands.DefineCommands" in this menu contribution.

 

 

Create the following class.

 

			
package de.vogella.rcp.commands.runtimecommands;

import org.eclipse.swt.SWT;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.CommandContributionItemParameter;
import org.eclipse.ui.menus.ExtensionContributionFactory;
import org.eclipse.ui.menus.IContributionRoot;
import org.eclipse.ui.services.IServiceLocator;

public class DefineCommands extends ExtensionContributionFactory {

	@Override
	public void createContributionItems(IServiceLocator serviceLocator,
			IContributionRoot additions) {
		CommandContributionItemParameter p = new CommandContributionItemParameter(
				serviceLocator, "",
				"org.eclipse.ui.file.exit",
				SWT.PUSH);
		p.label = "Exit the application";
		p.icon = Activator.getImageDescriptor("icons/alt_window_16.gif");

		CommandContributionItem item = new CommandContributionItem(p);
		item.setVisible(true);
		additions.addContributionItem(item, null);
	}

}

		

 

Run the example, your application should have the Exit command in the menu.

电路设计仿真软件:Mentor Graphics_(1).MentorGraphics电路设计仿真软件概述 菜单栏:包含文件、编辑、视图、工具等菜单。工具栏:提供常用的工具按钮,如打开、保存、仿真等。原理图编辑区:用于绘制电路原理图。元件库:包含各种电路元件,支持拖拽操作。属性面板:显示选中元件的属性,可以进行参数设置。仿真控制区:用于设置仿真参数和控制仿真过程。输出窗口:显示仿真结果和日志信息。打开模型编辑器:点击“工具”菜单,选择“模型编辑器”。选择模型类型:在模型编辑器中选择模型类型,如SPICE模型。输入模型参数:根据需要输入模型的参数,如电阻值、电容值等。保存模型。 阅读详情

相关推荐

RK3588嵌入式开发实战:U-Boot设备树文件修改全指南(含常见踩坑点)

本文为RK3588嵌入式开发者提供了一份详尽的U-Boot设备树文件修改实战指南。文章深入解析了设备树的核心架构,从基础硬件适配到时钟、电源管理等进阶配置,并重点总结了内存节点、串口输出、电源时序等常见踩坑点与解决方案,旨在帮助开发者高效、稳健地完成U-Boot移植与定制工作。

yhn456789的博客 732

Eclipse Commands 指南(二)

4.  命令和菜单上下文    现在让我们将ContextMenu添加到表。创建一个新的项目“de.vogella.rcp.intro.commands.popup”基于“RCP application with a view”的例子。创建一个ID为“de.vogella.rcp.intro.commands.popup.showSelected”的新Command,名称为“Show”。在这个例子中,我们将不使用default handler。因此,添加扩展点“org.eclipse.ui.handlers

redshlink的专栏 6134

决策树(分类树、回归树)

决策树 前言:第一篇博客,最近看完决策树,想着归纳一下,也方便自己以后回顾。写的会比较全面一些,可能会有很多不太正确的地方,欢迎大家交流指正 : ) 决策树模型: 决策树模型是运用于分类以及回归的一种树结构。决策树由节点和有向边组成,一般一棵决策树包含一个根节点、若干内部节点和若干叶节点。决策树的决策过程需要从决策树的根节点开始,待测数据与决策树中的特征节点进行比较,并按照比较结果选...

你午睡了吗 9万+

eclipse错误 timeout

错误提示: Failed to install helloworld.apk on device'emulator-5554': timeout 或者 the user data image is used 原因: 由于模拟器已经开启而没有关闭或者非法关闭引起的。 解决方法: 删除 C:\Documents and Settings\Administrator\.android\av

兜里有包包 775

Android Profiler 帧率优化实战与性能调优

本文详细介绍了使用Android Profiler进行帧率优化与性能调优的实战方法。通过分析主线程状态、FPS曲线和渲染阶段耗时,精准定位卡顿根源,并提供减少过度绘制、优化绘制命令及改善资源使用的具体策略。文章结合电商、游戏等真实案例,帮助开发者有效解决卡顿问题,提升应用流畅度。

palm99的专栏 536

Keystone变换(4)MATLAB仿真

关于Keystone变换三种方法(DFT-IFFT法、Sinc插值法和Chirp-Z法)的仿真

qq_45846079的博客 1570

Eclipse插件开发根据需要显示按钮或菜单

介绍 有时候我们需要根据特定的情况来决定是否要实现菜单或者按钮,换句话说只有满足特定要求的情况下再显示或者变成可用的。这时候,可以借助Eclipse的表达式框架。 表达式框架是在插件org.eclipse.core.expressions中实现的。 另外,Eclipse的表达式框架还...

chuannaoxuan4674的博客 550

ardupilot开发 --- Remote ID 篇

适配ardupilot的Remote ID模块研发,远程标识模块研发。Remote ID模块可以通过蓝牙或wifi向外广播无人机的状态信息、位置信息、任务信息等,并可以通过蜂窝数据向国家无人驾驶航空器一体化综合监管服务平台上报这些信息。Remote ID功能是21年起国家出台的民用无人机适航飞行的基本要求!

记录老板的每次pua,分享领导每天的毒鸡汤... 9607

动态生成command

目的:在程序运行时动态生成各菜单子项。 实现思路:通过menuContribution的class属性类实现。 步骤: 1、在org.eclipse.ui.menus中定义一个menuContribution项,同时通过locationURI设置此menuContribution的依附对象。 2、实现menuContribution项的class类。 注意此类必须继承自E

佛曰不可说 1402

Python全栈入门到实战【基础篇 22】生成器与迭代器:底层逻辑与实战场景

Python迭代器与生成器:惰性求值的高效实践 摘要:本文深入解析Python中迭代器和生成器的核心机制与应用场景。迭代器通过实现__iter__()和__next__()方法实现惰性求值,适合处理大数据集和无限序列。生成器作为迭代器的简化实现,通过yield关键字自动实现迭代器协议,代码更简洁。文章详细对比了可迭代对象与迭代器的区别,演示了自定义迭代器和生成器函数的实现方式,并介绍了生成器表达式这一高效替代列表推导式的方案。通过斐波那契数列等实例,展示了惰性求值在内存优化方面的优势,以及生成器在流式数据处

那些看似不起波澜的日复一日,会在某天让你看到坚持的意义 3262

Android 13.0 framework默认沉浸式导航栏功能实现

​ 在13.0的系统rom定制化开发中,在实现导航栏的某些定制化开发中,在某些产品需要实现沉浸式导航栏,就是需要app 能全屏显示同样也能显示导航栏,接下来就来分析下相关的功能实现 ​

安卓兼职framework和app工程师的博客 467

工具、菜单栏右对齐

方法一:指定menuContribution: toolbar:org.eclipse.ui.main.toolbar - the top-level tool bar toolbar:org.eclipse.ui.trim.command1 - the top left trim toolbar:org.eclipse.ui.trim.command2 - the top righ...

zhymin77的专栏 368

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

eclipse command java_Eclipse Command框架简明教程(PART-1)

Commands简介Command是组件的申明式描述,并且独立于具体实现。Command通过org.eclipse.ui.commands扩展点来定义。Command可以被分类、分配到UI,并且还可以定义Key Binding。Command的行为通过handler定义。与Command相关的扩展点为了定义Command,可以新建一个org.eclipse.ui.command扩展点的扩展。org...

weixin_36316102的博客 470

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Eclipse Action与Command的区别

eclipse的action和command都能够执行一段确定的代码。通过一个工具栏上的图标、菜单项都可以触发执行。Action框架已经被验证过了,集成的非常紧密,而且很容易实现。但是为什么要废弃action改成command呢? Actions     Actions主要关注的是表现形式,而且所有代码都在action中。尽管有些代码也分布在action代理中,但是本质上还是act

imu2008 1382

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

mac eclipse 修改 command+Q 防止误操作 应用

Android mac eclipse 修改 command+Q 防止误操作  单个应用修改 command Q  快捷键  应用mac 下 使用eclipse 经常不小心会按到 command+Q 从而关闭 eclipse  每次都要重新打开 eclipse 然后慢慢等待.....这种误操作简...

yonghongbin的专栏 225

Eclipse 4.x中Command是如何映射到Handler的

1. Eclipse中的Command模式,使得具体的实现和Command定义分离,便于维护。 但是在Debug的时候,或者没有souce code的时候,我们想知道每一个commandId对应的Handler是什么,怎么办? 2. 在Eclipse 4.x中,其实当Eclipse启动完成后,它已经创建了commandId和对应Handler的Map,保存在EclipseContext中,

贾亮的专栏 1671

Eclipse RCP Command的Handler设置不起作用?

网上很多种教程教我们设置Command的Handler从而可以有效的控制Command的使用状态,比如只针对某种类型文件启用Command等。但当我们按教程上一步步试用时,却看不到期望的效果,command总是一直出现,不能随着Handler的设置而变化。如以下的Handler:

Neil的专栏 2983

mac eclipse 修改 command+Q 防止误操作 应用

Android mac eclipse 修改 command+Q 防止误操作 单个应用修改 command Q 快捷键 应用 mac 下 使用eclipse 经常不小心会按到 command+Q 从而关闭 eclipse 每次都要重新打开 eclipse 然后慢慢等待..... 这种误操作简直是反人类...... 查了很多帖子终于找到 仅修改 单个应用快捷键的方法 再也不用担心 开发的时候按到 command+Q 退出了 修改步骤: 系统偏好设置 -> 键盘 -> 快捷

提升心智 1万+

blog220123.Eclipse ui之command, handler, menu, 和binding的extPoints

blog220123.Eclipse ui之command, handler, menu, 和binding的extPointsCommands, extP="org.eclipse.ui.commands"Handlers, extP="org.eclipse.ui.handlers",Bindings, extP="org.eclipse.ui.bindings"Menus, extP="org.eclipse.ui.menus" 本文以eclipse 4.20为参考. 使用extension poin

骐骥一跃的博客 638

Eclipse的Command应用教程(一)

Eclipse Commands This article describes the usage of Eclipse commands. It describes how to create commands, handlers, add commands into the menu, pop-ups, views and editors and the usage of e...

沧海一粟 606

Command的学习

昨天特意看了一下Eclipse的技巧,又一次体会到了它的强大,呵呵.import javax.microedition.lcdui.Choice;import javax.microedition.lcdui.Command;import javax.microedition.lcdui.CommandListener;import javax.microedition.lcdui.Displ

AOL's Web Log 2307

Eclipse EMF教程(下)

翻译自:https://eclipsesource.com/blogs/tutorials/emf-tutorial/在接下来的部分中,我们将探索我们生成的代码的EMF API。

一念天堂 1323

Eclipse Command框架简明教程(PART-1)

原文出处:http://www.vogella.com/articles/EclipseCommands/article.html Commands 简介 Command是组件的申明式描述,并且独立于具体实现。Command通过org.eclipse.ui.commands扩展点来定义。 Command可以被分类、分配到UI,并且还可以定义Key Bindi...

weixin_30673715的博客 86
上一篇: Eclipse的Command应用教程(一)
tkxing
博客等级 码龄19年 1粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值