XWT - 事件处理

在我的上一篇文章中介绍了XWT的Hello World入门例子,接下来我们将了解一下XWT的事件处理。
先写个简单例子
<Shell xmlns="http://www.eclipse.org/xwt/presentation"
xmlns:x="http://www.eclipse.org/xwt"
x:Class="ui.EventHandler">
<Shell.layout>
<GridLayout/>
</Shell.layout>
<Button text="Click Me!" SelectionEvent="clickButton">
</Button>
</Shell>

 
通过扩展属性x:Class定义了处理事件的Java类,但点击按钮时,触发SelectionEvent事件,这时会调用EventHandler的clickButton方法:
package ui;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Button;

public class EventHandler {
protected void clickButton(Event event) {
Button button = (Button )event.widget;
button.setText("Hello, world!");
}
}

    程序运行的结果就是按钮的文字变成了“Hello, world!”。

    这个例子展示了XWT可以链接到Java CLR(Common Language Runtime)的实例,使用x:Class将UI和Java类联系到了一起  。

image_thumb

 
CLR with x:ClassFactory

   其实你也可以使用c:ClassFactory来连接你的CLR Factory。

<Shell xmlns="http://www.eclipse.org/xwt/presentation"
xmlns:x="http://www.eclipse.org/xwt"
x:ClassFactory="xwt.samples.ui.EventHandlerFactory">
<Shell.layout>
<GridLayout/>
</Shell.layout>
<Button text="Click Me!" SelectionEvent="clickButton">
</Button>
</Shell>

使用x:ClassFactory属性指定了与UI进行连接的是xwt.samples.ui.EventHandlerFactory.java这个类。

package xwt.samples.ui;

import java.beans.EventHandler;
import java.util.Map;

import org.eclipse.e4.xwt.ICLRFactory;

public class EventHandlerFactory implements ICLRFactory {

@Override
public Object createCLR(String args, Map<String, Object> options) {
return new SampleEventHandler();
}
}

其实你也可以在x:ClassFactory指定参数,比如:

x:ClassFactory="xwt.samples.ui.EventHandlerFactory bean=myCLR"

运行时,EventHandlerFactory 的createCLR方法的args参数将会变成“bean=myCLR”了,你可以通过这个控制程序的跳转。

posted @ 2011-07-14 15:06  vwpolo  阅读(1263)  评论(0编辑  收藏  举报