第一次做了Java GUI,我选择用elipse自己的前段开发工具 SWT/JFace。这篇文章是基于eclipse MARS.2. 用SWT编写的GUI的风格如下:
1、 SWT中的一些概念
1.1 Display & Shell
Display 和 Shell 类是SWT中重要的组件。 org.eclipse.swt.widgets.Shell 这个类代表窗口。org.eclipse.swt.widgets.Display主要负责时间循环、字体、颜色、UI线程和其他线程之间的通信(这个功能非常重要,在后面的例子中会说到,UI 线程和非UI线程之间通信,如果不获取Display的话,会报”无法访问线程“的错误)。Display 是左右SWT组件的基础。
每个SWT应用要求至少有一个Display 和一个或多个shell对象。主窗口shell的构造函数把Display作为默认参数。例如:
Display display = new Display();
Shell shell = new Shell(display);
shell.open();
// run the event loop as long as the window is open
while (!shell.isDisposed()) {
// read the next OS event queue and transfer it to a SWT event
if (!display.readAndDispatch())
{
// if there are currently no other OS event to process
// sleep until the next OS event is available
display.sleep();
}
}
// disposes all associated windows and their components
display.dispose();
1.2 SWT 窗口中的部件
SWT编写程序的窗口部件都在包org.eclipse.swt.widgets 和 org.eclipse.swt.custom中, 下图是是一些部件的图样:
2 在eclipse中编写一个简单的SWT的例子
2.1 创建一个RCP Plugin Progect
在eclipse中选择File/New/Other...
- 不需要创建Workbenck应用,所以选择下图的 1 所示的选项
- 在下图 2 的地方选择”yes“,否则创建一个web应用

创建一个工程:
添加依赖的库文件
2.2 编写例子
这是一个简单的例子,没用用WindowBuilder工具(可以用拖拽的方式制作界面的布局)
- HelloSWT.java
package org.o7planning.tutorial.swt.helloswt;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class HelloSWT {
public static void main(String[] args) {
// Create Display
Display display = new Display();
// Create Shell (Window) from diplay
Shell shell = new Shell(display);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
右键点击HelloSWT类,选择Run As/Java Application.
结果如下: 一个空的窗口
下面一篇文章是用Window Buider 构建一个SWT的桌面应用。