//这个程序是一个最简单的SWT窗口
//注意:在选择"Create contents in"选项的时候选择"public static main()method"
//程序中需要import的类都写在代码的最开始处,可以通过右键菜单“源代码”->"组织导入"让Eclipse自动添加。
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class HelloWorldSWT
{
private static Text helloWorldSwtText;
public static void main(String[] args)
{
//display负责管理事件循环和控制UI线程和其他线程之间的通信,下面是display class的介绍
/***************************
*Instances of this class are responsible for managing the connection between SWT and the underlying operating system.
*Their most important function is to *implement the SWT event loop in terms of the platform event model.
*They also provide various methods for accessing information about the operating *system,
*and have overall control over the operating system resources which SWT allocates.
***************************/
Display display = new Display();
//你可以把shell当作是应用程序的窗口,一个容器填充了很多控件,下面是shell class的介绍
/***************************
*Instances of this class represent the "windows" which the desktop or "window manager" is managing.
*Instances that do not have a parent (that is, they are built using the constructor,
*which takes a Display as the argument) are described as top level shells.
*Instances that do have a parent are described as secondary or dialog shells.
***************************/Eclipse SWT例程分析(一
Shell swtApplicationShell = new Shell(display);
swtApplicationShell.setText("SWT Application");//窗口标题
swtApplicationShell.setSize(300, 100);//窗口大小
//----------------Begin 手动添加的内容
helloWorldSwtText = new Text(swtApplicationShell, SWT.BORDER);//创建句柄
helloWorldSwtText.setText("Hello World SWT");//设置文本内容
helloWorldSwtText.setBounds(75, 20, 140, 25);//设置坐标
//----------------End
swtApplicationShell.layout();//布置应用界面
swtApplicationShell.open();//显示应用窗口
while(!swtApplicationShell.isDisposed())//如果主窗口没有关闭将一直循环
{
if(!display.readAndDispatch())//如果display不忙
{
display.sleep();//休眠
}
}
display.dispose();//销毁display
}
}
可以看到一个最简单SWT应用程序主要有以下几个部分
1、声明display、shell句柄,display负责消息循环,shell负责窗口布局
2、在shell容器中填充我们需要的控件,如果需要可以添加事件监听程序
3、消息循环
4、销毁display
这个程序是我接触到的第一个SWT应用程序,目前我也正在学习SWT,以后会逐步把我遇到的代码拿出来进行分析,当然主要是网络中的开源程序。