2017-04-26 58 views

回答

1

顯示SWT Table標題的右鍵單擊菜單以獲取列名稱或索引。

SWT.MenuDetect:當檢測到顯示菜單項的平臺相關觸發器時發送。

table.addListener(SWT.MenuDetect,new Listener() { 
     @Override 
     public void handleEvent(Event e) { 
      Point ptAbsolute = new Point(e.x, e.y); 
      Point pt = table.toControl(ptAbsolute); 
      int colIndex = columnAtPoint(table, pt); 
      if (colIndex >= 0) { 
       if (pt.y < table.getHeaderHeight()) { 
        // Negative Y means table header 

        System.out.println("Column name is " + table.getColumn(colIndex).getText()); 
       } 
       else { 
        System.out.println("Row right-clicked on column name is " + table.getColumn(colIndex).getText()); 
       } 
      } 
     } 
}); 

Point:表示(x,y)座標空間中的位置的點,以整數精度指定。

private static int columnAtPoint(Table table, Point pt) { 
    int colIndex = -1; 

    TableItem fakeRow = new TableItem(table, 0); 
    for (int i = 0; i < table.getColumnCount(); i++) { 
     Rectangle rec = fakeRow.getBounds(i); 
     if ((pt.x > rec.x) && (pt.x < (rec.x + rec.width))) { 
      colIndex = i; 
     } 
    } 
    fakeRow.dispose(); 
    return colIndex; 
} 
3

下面是一些代碼,會打印點擊TableColumn頭:如果您需要索引

public static void main(String[] args) 
{ 
    final Display display = new Display(); 
    final Shell shell = new Shell(display); 
    shell.setLayout(new FillLayout()); 

    Table table = new Table(shell, SWT.NONE); 
    table.setHeaderVisible(true); 

    for (int i = 0; i < 3; i++) 
    { 
     new TableColumn(table, SWT.NONE).setText("Column " + i); 
    } 

    for (int j = 0; j < 10; j++) 
    { 
     TableItem item = new TableItem(table, SWT.NONE); 
     for (int i = 0; i < table.getColumnCount(); i++) 
     { 
      item.setText(i, "Cell " + j + " " + i); 
     } 
    } 

    for (int i = 0; i < table.getColumnCount(); i++) 
    { 
     table.getColumn(i).pack(); 
    } 

    table.addListener(SWT.MenuDetect, e -> 
    { 
     Point pt = Display.getCurrent().map(null, table, new Point(e.x, e.y)); 
     Rectangle clientArea = table.getClientArea(); 
     boolean headerClicked = (clientArea.y <= pt.y && pt.y < (clientArea.y + table.getHeaderHeight())); 

     if (headerClicked) 
     { 
      int xOffset = 0; 
      for (int colIdx : table.getColumnOrder()) 
      { 
       int colWidth = table.getColumn(colIdx).getWidth(); 

       if (xOffset <= pt.x && pt.x < (xOffset + colWidth)) 
       { 
        System.out.println(table.getColumn(colIdx).getText()); // Your code goes here 
        break; 
       } 
       xOffset += colWidth; 
      } 
     } 
    }); 

    shell.pack(); 
    shell.open(); 

    while (!shell.isDisposed()) 
    { 
     if (!display.readAndDispatch()) 
     { 
      display.sleep(); 
     } 
    } 
} 

使用colIdx

+0

感謝bro..this答案是非常有用的...好 –

+0

你的代碼是limited..large列名獲得唯一可見的列名,但滾動條滾動的列名不正確的工作(獲得列名)..我發佈此代碼有用...感謝巴茲 –