Welcome 微信登录

首页 / 软件开发 / JAVA / SWT/JFace入门指南之让SWT程序动起来

SWT/JFace入门指南之让SWT程序动起来2011-01-04我不知道大家有没有这样的体验:其实软件使用者要求的东西都很基本,而现在软件做得越来越复杂,有相当大一部分是在于软件开发者把自己的注意力放在了一些附加功能(这些功能可能让用户感到惊喜,但是如果没有它们用户也不会不满意)上,而真正用户的要求却得不到满足。所以大家在设计程序的时候,一定要明白,有时候简单就是一种美,把时间花费到真正有价值的地方去。

OK,回到我们的主题上来。在这一节中,我将给大家介绍swt的事件模式。在前面我们也提到过,写一个swt程序,无非就是分几步走。其中比较需要费心的就是布置好用户界面和处理各种事件。

添加了事件处理的Hello,world!

其实swt中处理事件非常简单,对应于各种事件都有相应的listener类,如果一种事件叫做Xyz,那么对应的listener类就是XyzListener。比如对应于鼠标事件的有MouseListener,对应于键盘事件的就是KeyListener。而在每种widget中,对于它可以处理的事件都有addXyzListener方法,只要把对应的listener实例作为参数传给它就可以了。

为了更加清楚的说明,我们先来看下面一段程序:

1 public class EventDemo {
2
3 private Shell _shell;
4
5 public EventDemo() {
6 Display display = new Display();
7 Shell shell = new Shell(display,SWT.SHELL_TRIM);
8 setShell(shell);
9 RowLayout layout=new RowLayout();
10 shell.setLayout(layout);
11 shell.setText("Event demo");
12
13 Button button=new Button(shell,SWT.PUSH | SWT.CENTER);
14 button.setText("Click me!");
15
16 button.addSelectionListener(new SelectionListener(){
17
18 public void widgetSelected(SelectionEvent event) {
19 handleSelectionEvent();
20 }
21
22 public void widgetDefaultSelected(SelectionEvent event) {
23 }
24 });
25 shell.setBounds(200,300,100,100);
26 shell.open();
27
28 while (!shell.isDisposed()) {
29 if (!display.readAndDispatch()) {
30 display.sleep();
31 }
32 }
33 display.dispose();
34
35 }
36
37 protected void handleSelectionEvent() {
38 MessageBox dialog=new MessageBox(getShell(),SWT.OK|SWT.ICON_INFORMATION);
39 dialog.setText("Hello");
40 dialog.setMessage("Hello,world!");
41 dialog.open();
42 }
43
44 /**
45 * @param args
46 */
47 public static void main(String[] args) {
48
49 EventDemo eventdemo=new EventDemo();
50 }
51
52 /**
53 * @return Returns the _shell.
54 */
55 public Shell getShell() {
56 return _shell;
57 }
58
59 /**
60 * @param _shell The _shell to set.
61 */
62 public void setShell(Shell shell) {
63 this._shell =shell;
64 }
65 }
66