有些组件在大多数操作系统都存在,SWT直接通过JNI直接封装了这些组件。
按钮
Button(按钮)是SWT组件常用的一种。在组件中添加一个按钮很简单,只需要指定按钮的父组件和相应的样式即可,例如:“Button button = new Button(shell, SWT.PUSH)”语句在shell组件中添加了一个普通的按钮。
另外,添加一个按钮一般来说会指定按钮的位置(如果未指定布局信息)和按钮的显示标签,如例程1所示。
例程1 HelloWorldButton.java
/** * 为了节省篇幅,所有的import类已经被注释 * 读者可以通过ctrl+shift+o快捷键,自动引入所依赖的类 * 如果有问题可发邮件到ganshm@gmail.com * */ public class HelloWorldButton { public HelloWorldButton() { Display display = new Display(); Shell shell = new Shell(display); //指定父组件和按钮样式 Button button = new Button(shell, SWT.PUSH); //指定按钮的位置 button.setBounds(40, 50, 100, 30); //指定按钮的显示标签 button.setText("Click Me"); shell.setSize(200, 200); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } public static void main(String[] args) { new HelloWorldButton(); } }
上例中展示了如何在一个窗口中添加一个按钮,程序运行效果如图2所示。

图2 按钮组件
按钮的样式有很多种,在SWT中,CheckBox(复选框)和RadioBox(单选框)都是不同样式的按钮。
提示:如果按钮为复选框或单选框,可以通过“getSelection”方法判断按钮是否被选中。
标签
Lable(标签)是SWT组件常用的组件之一。在组件中添加一个标签很简单,只需要指定按钮的父组件和相应的样式即可,例如“Label label = new Label(shell, SWT.SEPARATOR | SWT.VERTICAL)”语句在shell组件中添加了一个标签。
可以为SWT组件指定复合样式,SWT将按复合样式显示组件,如标签示例,例程2所示。
例程2 HelloWorldLabel.java
public class HelloWorldLabel { public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); Label label1 = new Label(shell, SWT.WRAP); label1.setText("very good!"); new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); new Label(shell, SWT.SEPARATOR | SWT.VERTICAL); Label label2 = new Label(shell, SWT.NONE); label2.setText("very good!"); shell.setSize(200, 70); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
上例窗口中添加了4个标签,并为每个标签设置了不同的显示样式,程序运行效果如图3所示。

图3 标签组件
标签可以作为显示文本的组件,也可以作为分隔符,如果作为分隔符,标签不显示文字信息。