3

在 Eclipse SWT 领域,当您可以向控件添加多种样式时,它会派上用场。工具栏可以添加多种样式。工具物品不能享受同样的特权吗?解决方案的工作是什么?

ToolItem API 明确指出

只能指定 CHECK、PUSH、RADIO、SEPARATOR 和 DROP_DOWN 样式之一。

基本上,我希望有一个工具栏项,其行为类似于带有下拉菜单的单选按钮。我希望用户能够从下拉列表中的项目列表中更改项目的默认操作。

谁能给我指出正确的方向?

    ...
    ToolBar toolBar = new ToolBar(composite, SWT.FLAT | SWT.RIGHT | SWT.HORIZONTAL);

    ToolItem item1 = new ToolItem(toolBar, SWT.RADIO);
    item1.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            // do something
        }
    });
    item1.setImage(image1);

    ToolItem item2 = new ToolItem(toolBar, SWT.RADIO | STW.DROP_DOWN); //only allowed in my dreams
    item2.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            // do a drop down action and lots more.
            // change image of this ToolItem to match the drop down selection.
            item2.setImage(selectedImage);
        }

    });
    item2.setImage(image2);
4

1 回答 1

1

代码段显示了如何创建下拉菜单。要获得单选按钮,请对 MenuItem 使用 SWT.RADIO 样式而不是 SWT.PUSH。

final ToolBar toolBar = new ToolBar (shell, SWT.NONE);
Rectangle clientArea = shell.getClientArea ();
toolBar.setLocation(clientArea.x, clientArea.y);
final Menu menu = new Menu (shell, SWT.POP_UP);
for (int i=0; i<8; i++) {
    MenuItem item = new MenuItem (menu, SWT.PUSH);
item.setText ("Item " + i);
}
final ToolItem item = new ToolItem (toolBar, SWT.DROP_DOWN);
item.addListener (SWT.Selection, new Listener () {
    public void handleEvent (Event event) {
        if (event.detail == SWT.ARROW) {
        Rectangle rect = item.getBounds ();
    Point pt = new Point (rect.x, rect.y + rect.height);
    pt = toolBar.toDisplay (pt);
    menu.setLocation (pt.x, pt.y);
    menu.setVisible (true);
        }
}
});
toolBar.pack ();
于 2013-08-22T14:33:21.213 回答