首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

SWT 實現 ToolBar 下拉式選單按鈕 (Drop-down ToolItem)

     編輯:Java 相關知識

核心代碼片段

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

關鍵點解析

  1. ToolItem 風格 SWT.DROP_DOWN 會顯示下拉箭頭。
  2. 彈出選單用 SWT.POP_UP 風格。
  3. 監聽 SWT.Selection,判斷 event.detail == SWT.ARROW 區分「點擊主體」與「點擊箭頭」。
  4. 座標轉換:getBounds() 取相對 ToolBar 座標 → toDisplay() 轉螢幕絕對座標 → menu.setLocation() 定位顯示。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved