核心代碼片段
final ToolItem dropdown = new ToolItem(bar, SWT.DROP_DOWN);
dropdown.setText("Drop-down");
final Menu menu = new Menu(shell, SWT.POP_UP);
new MenuItem(menu, SWT.PUSH).setText("Choices");
dropdown.addListener(SWT.Selection, event -> {
// 僅點擊箭頭區域 (SWT.ARROW) 才彈出選單
if (event.detail == SWT.ARROW) {
Rectangle bounds = dropdown.getBounds();
Point pt = new Point(bounds.x, bounds.y + bounds.height);
pt = bar.toDisplay(pt); // 轉為螢幕座標
menu.setLocation(pt.x, pt.y);
menu.setVisible(true);
}
});
關鍵點解析
ToolItem 風格 SWT.DROP_DOWN 會顯示下拉箭頭。
- 彈出選單用
SWT.POP_UP 風格。
- 監聽
SWT.Selection,判斷 event.detail == SWT.ARROW 區分「點擊主體」與「點擊箭頭」。
- 座標轉換:
getBounds() 取相對 ToolBar 座標 → toDisplay() 轉螢幕絕對座標 → menu.setLocation() 定位顯示。