技术开发 频道

了解TabFolder、Canvas和其他多种控件

  有时,当您希望能够将一个选择列表显示为一个弹出式菜单而不用创建一个弹出式菜单时,可以使用 PopupList 控件做到这一点。图 6 显示了如何使用此控件将选择、剪切、复制和粘贴功能添加到 图 5 的文本编辑器中。

  图 6. PopupList 的例子

  清单 13 显示了 processPopup 方法的内容。注意,安置弹出式菜单的代码与它所涉及的控件(即样式文本)有关。

  清单 13. PopupList 的例子

1 PopupList popup = createPopupList(shell, 50, popupItems);
2 popup.select(popupItems[0]);
3 Point p = styledText.getLocation();
4 p = shell.getDisplay().map(styledText, null, p.x, p.y);
5 String choice = popup.open(new Rectangle(
6                     p.x + 100, p.y - 100, 100, 200));
7 if (choice != null) {
8     if      (popupItems[0].equals(choice)) {
9         styledText.selectAll();
10     }
11     else if (popupItems[1].equals(choice)) {
12         styledText.cut();
13     }
14     else if (popupItems[2].equals(choice)) {
15         styledText.copy();
16     }
17     else if (popupItems[3].equals(choice)) {
18         styledText.paste();
19     }
20 }
21 :
22 protected static final String[] popupItems = {
23     "Select All", "Cut", "Copy", "Paste"
24 };

 

  StackLayout

  在前两篇文章中,我讨论了随 SWT 一起提供的几个布局管理器,其中包括 FillLayout、GridLayout 和 FormLayout。custom 包提供了 StackLayout,可以用它在一次只显示一个 GUI 的 TabFolder(有些类似于没有选项卡的 TabFolder)的顶部放置多个 GUI。考虑一下 图 7 和 图 8,它们显示了一个显示带编号标签的堆栈布局的两种状态。通过“>>”按钮可以让堆栈前进,而通过“<<”按钮则可以让堆栈后退。图 8 显示了按下“>>”按钮 4 次后的布局。

  图 7. StackLayout 的例子 1

  图 8. StackLayout 的例子 2

  此堆栈由清单 14 中的代码创建。

  清单 14. StackLayout 的例子

1 StackLayout stackLayout = new StackLayout();
2 Composite clabels = createComposite(body, SWT.BORDER,
3                                     stackLayout);
4 Label[] labels = new Label[5];
5 :
6 for (int i = 0; i < labels.length; i++) {
7     Label xlabel = new Label(clabels, SWT.CENTER);
8     xlabel.setText("Stack " + i);
9     labels[i] = xlabel;
10 }
11 stackLayout.topControl = labels[0];
12 :
13 protected Composite createComposite(Composite parent,
14                                     int style,
15                                     Layout layout) {
16     Composite c =  new Composite(parent, style);
17     if (layout != null) {
18         c.setLayout(layout);
19     }
20     return c;
21 }
22 protected Composite createComposite(Composite parent,
23                                     Layout layout) {
24     return createComposite(parent, SWT.NONE, layout);
25 }
26

 

  清单 15 显示了通过“>>”按钮到达下一个堆栈的代码。对于“<<”按钮,代码与此类似。

  清单 15. 前进到下一个堆栈的代码

1 protected int currentLabel;
2 public void doNext() {
3     ++currentLabel;
4     if (currentLabel >= labels.length) {
5         currentLabel = 0;
6     }
7     stackLayout.topControl = labels[currentLabel];
8     clabels.layout();
9 }
10

 

  结束语

  在 SWT 和 JFace 系列的第三期中,我介绍了更多的 SWT 控件,比如用于创建表树的 Tree;用于绘图的 Canvas;用于输入数字值的 Slider、Scale 和 Spinner;用于显示进度的 ProgressBar;用于输入具有某些属性的文本的 StyledText;以及用于简单动态菜单的 PopupList。我还展示了如何使用 StackLayout 创建时间合理的重叠 GUI。本系列的下一期将展示如何使用更多的 SWT 控件。

  代码下载:os-Samples-SWT3.ZIP

0
相关文章