简体   繁体   中英

How do I create an eclipse toolbar item with SWT.RADIO style with drop-down capabilities?

In eclipse SWT land, it comes in handy when you can add multiple styles to controls. Toolbars can have multiple styles added. Can't tool items enjoy the same privilege? What is the work around solution?

The ToolItem API clearly states that

Only one of the styles CHECK, PUSH, RADIO, SEPARATOR and DROP_DOWN may be specified.

Basically, I would like to have a toolbar item to behave like a radio button with a drop down. I want users to be able to change an item's default action from a list of items in its drop down.

Can anyone kindly point me in the right direction?

    ...
    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);

This snippet shows how to create a drop down menu. To get the radio buttons, use the SWT.RADIO style instead of SWT.PUSH for the MenuItems.

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 ();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM