RCP handler处理函数中获取当前选择项。

目的:在command的处理函数中获取触发当前command时被选中的条目。


方法:使用HandlerUtil工具类获取。


代码示例:

	public Object execute(ExecutionEvent event) throws ExecutionException {
		// 获取需要导出的线路。
		ISelection selection = HandlerUtil.getCurrentSelection(event);

		System.out.println(selection);
		
		PowerLineInfo pl = (PowerLineInfo)((IStructuredSelection)selection).getFirstElement();

		System.out.println((pl).getPowerLineName());


原理解析:

查看HandlerUtil.GetCurrentSelection函数,可发现其实现为:

	public static ISelection getCurrentSelection(ExecutionEvent event) {
		Object o = getVariable(event, ISources.ACTIVE_CURRENT_SELECTION_NAME);
		if (o instanceof ISelection) {
			return (ISelection) o;
		}
		return null;
	}

其中:

org.eclipse.ui.ISources.ACTIVE_CURRENT_SELECTION_NAME 值为 "selection"

其为RCP框架内置的一个变量,由框架维护其值的变化。

再看getVariable的函数实现:

	/**
	 * Extract the variable.
	 * 
	 * @param event
	 *            The execution event that contains the application context
	 * @param name
	 *            The variable name to extract.
	 * @return The object from the application context, or <code>null</code>
	 *         if it could not be found.
	 */
	public static Object getVariable(ExecutionEvent event, String name) {
		if (event.getApplicationContext() instanceof IEvaluationContext) {
			Object var = ((IEvaluationContext) event.getApplicationContext())
					.getVariable(name);
			return var == IEvaluationContext.UNDEFINED_VARIABLE ? null : var;
		}
		return null;
	}

从中可得知HandlerUtil获取当前选择的处理思路:

通过event获取当前执行上下文环境,然后在此上下文环境中检索selection状态值。


从以上分析可知,如果想使用HandlerUtil工具类获取当前选择项,事件的触发源容器必须将自身注册为selectionProvider。



到此产生了一个问题:假如Selection提供者无法将自身注册为selectionProvider,或者Selection处理函数不是event处理函数,即没法使用HandlerUtil的工具函数,那么该如何获取selection呢?

解决思路可借鉴HandlerUtil的设计,即使用状态来传递selection。

为了能使用状态,我们需要先自定义一个SourceProvider类,由其来保管需要传递的状态,并在状态改变时通过监听机制通知各监听者。

选择项的提供者在产生选择项时,通过RCP框架获取到对应的状态管理SourceProvider类实例,然后将选择项交给此SourceProvider,由其进行后续操作。

对前述选择项感兴趣的其他类可将自身(需要实现ISourceProviderListener接口)注册到前面定义SourceProvider类示例,然后在sourceChanged函数中处理接收到的选择项。


后面的这个分析有点问题,至少对于前面假设的情况而言是绕了弯路的,其实在前述假设的情况下,Selection提供者可以将自己定义为事件分发者,对Selection感兴趣者可将自身作为监听者注册到Selection提供者,也能达到交流Selection的目的,而且效率更高。


参考资料:

1、eclipse rcp:how to pass selection into handler

2、RCP 自定义用于visible/enable when表达式的变量

3、Eclipse Commands Advanced - Tutorial



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值