SWT:单击工具栏按钮后显示弹出菜单

时间:2011-06-09 14:48:12

标签: swt toolbar popupmenu

当用户点击此按钮时,我想在工具栏按钮下方显示一个弹出菜单。我已经了解了SWT.DROP_DOWN的{​​{1}}样式,但这似乎仅限于根据this sample的简单项目列表。相反,我想显示一个弹出菜单,例如复选框和单选按钮菜单项。

1 个答案:

答案 0 :(得分:8)

您可以使用样式SWT.CHECK,SWT.CASCADE,SWT.PUSH,SWT.RADIO,SWT.SEPARATOR创建MenuItem see 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();
}

}