2011-06-09 51 views

回答

8

您可以用菜單項風格SWT.CHECK,SWT.CASCADE,SWT.PUSH,SWT.RADIO,SWT.SEPARATOR 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(); 
} 

} 
+0

BTW工具欄項,有可能是'SWT.DROP_DOWN'的工具欄按鈕的正常按鈕點擊(這應該直接調用的動作)之間進行區分並點擊下拉區域(其應該顯示下拉菜單)? – Mot 2011-06-16 14:41:00

+1

是的。作爲listener方法的參數的'SelectionEvent e'具有屬性'e.detail',如果按下按鈕則爲'0',如果按下箭頭則屬性爲'4'(即'SWT.ARROW'的值) 。 – Sorceror 2011-06-17 07:32:55

+0

值得注意的是,'setLocation()'方法也可以接受'Point',這樣就可以執行'dropMenu.setLocation(toolBar.toDisplay(new Point(ex,ey)));',如果你進入那種單線編程。 – krispy 2014-05-28 17:34:58

相關問題