【问题标题】:SWT: show popup menu below toolbar button after clicking on itSWT:单击工具栏按钮后在工具栏按钮下方显示弹出菜单
【发布时间】:2011-06-13 16:53:56
【问题描述】:

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

【问题讨论】:

    标签: swt toolbar popupmenu


    【解决方案1】:

    您可以使用样式 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();
    }
    
    }
    

    【讨论】:

    • 顺便说一句,SWT.DROP_DOWN 工具栏按钮是否可以区分单击普通按钮(应直接调用操作)和单击下拉区域(应显示下拉菜单)?
    • 是的。您作为侦听器方法的参数获得的SelectionEvent e 具有属性e.detail,如果按下按钮则为0,如果按下箭头则为4SWT.ARROW 的值)。
    • 值得注意的是,setLocation() 方法也可以接受Point,如果您喜欢这种单行编程,则可以执行dropMenu.setLocation(toolBar.toDisplay(new Point(e.x, e.y)));
    猜你喜欢
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2015-08-29
    相关资源
    最近更新 更多