2

当用户单击此按钮时,我想在工具栏按钮下方显示一个弹出菜单。我已经阅读了SWT.DROP_DOWNa 的样式,ToolItem但这似乎非常仅限于根据此示例的简单项目列表。相反,我想显示一个弹出菜单,例如复选框和单选按钮菜单项。

4

1 回答 1

8

您可以使用样式 SWT.CHECK、SWT.CASCADE、SWT.PUSH、SWT.RADIO、SWT.SEPARATOR 制作 MenuItem 参见 javadoc ..

因此,您可以像这样“挂起” swt 菜单来选择工具栏项上的下拉菜单

public class Test {

private Shell shell;

public Test() {
    Display display = new Display();
    shell = new Shell(display, SWT.SHELL_TRIM);
    shell.setLayout(new FillLayout(SWT.VERTICAL));
    shell.setSize(50, 100);

    ToolBar toolbar = new ToolBar(shell, SWT.FLAT);
    ToolItem itemDrop = new ToolItem(toolbar, SWT.DROP_DOWN);
    itemDrop.setText("drop menu");

    itemDrop.addSelectionListener(new SelectionAdapter() {

        Menu dropMenu = null;

        @Override
        public void widgetSelected(SelectionEvent e) {
            if(dropMenu == null) {
                dropMenu = new Menu(shell, SWT.POP_UP);
                shell.setMenu(dropMenu);
                MenuItem itemCheck = new MenuItem(dropMenu, SWT.CHECK);
                itemCheck.setText("checkbox");
                MenuItem itemRadio = new MenuItem(dropMenu, SWT.RADIO);
                itemRadio.setText("radio1");
                MenuItem itemRadio2 = new MenuItem(dropMenu, SWT.RADIO);
                itemRadio2.setText("radio2");
            }

            if (e.detail == SWT.ARROW) {
                // Position the menu below and vertically aligned with the the drop down tool button.
                final ToolItem toolItem = (ToolItem) e.widget;
                final ToolBar  toolBar = toolItem.getParent();

                Point point = toolBar.toDisplay(new Point(e.x, e.y));
                dropMenu.setLocation(point.x, point.y);
                dropMenu.setVisible(true);
            } 

        }

    });

    shell.open();

    while(!shell.isDisposed()) {
        if(!display.readAndDispatch()) display.sleep();
    }

    display.dispose();
}

public static void main(String[] args) {
    new Test();
}

}
于 2011-06-13T08:53:56.050 回答