如何为SWT Table添加列(Column)菜单

来源:互联网 发布:网络教育本科升研究生 编辑:程序博客网 时间:2024/05/16 15:34

    为一个Table添加菜单后,当右击该Table的某一行,即可弹出定义好的菜单,这个不难做到。今天碰到一需求:需要针对Table的某一列(Column)的单元格添加右键菜单,也即:只有在右键单击某一列的单元格时,才在被选中的单元格上显示出该右键菜单。为实现这一需求,我们需要使用org.eclipse.swt.custom包中的TableCursor类,示例代码如下:
  1.     public static void main(String[] args) {
  2.         Display display = new Display();
  3.         Shell shell = new Shell(display);
  4.         shell.setLayout(new GridLayout());

  5.         // create a a table with 3 columns and fill with data
  6.         final Table table = new Table(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE);
  7.         table.setLayoutData(new GridData(GridData.FILL_BOTH));
  8.         int columnSize = 3;
  9.         TableColumn column;
  10.         for (int i = 0; i < columnSize; i++) {
  11.             column = new TableColumn(table, SWT.NONE);
  12.             column.setWidth(100);
  13.             column.setText("Column" + i);
  14.             column.pack();
  15.         }
  16.         table.setHeaderVisible(true);
  17.         for (int i = 0; i < 10; i++) {
  18.             TableItem item = new TableItem(table, SWT.NONE);
  19.             item.setText(new String[] { "cell" + i + "0""cell" + i + "1""cell" + i + "2" });
  20.         }

  21.         final TableCursor cursor = new TableCursor(table, SWT.NONE);
  22.         cursor.setBackground(table.getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION));
  23.         cursor.setForeground(table.getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT));
  24.         cursor.setLayout(new FillLayout());
  25.         final Menu menu = new Menu(table);
  26.         MenuItem item = new MenuItem(menu, SWT.PUSH);
  27.         item.setText("Hello Menu");
  28.         cursor.addSelectionListener(new SelectionAdapter() {

  29.             public void widgetSelected(SelectionEvent e) {
  30.                 int column = cursor.getColumn();
  31.                 if (column == 1) {
  32.                     table.setMenu(menu);
  33.                 } else {
  34.                     table.setMenu(null);
  35.                 }
  36.             }
  37.         });

  38.         shell.open();
  39.         while (!shell.isDisposed()) {
  40.             if (!display.readAndDispatch())
  41.                 display.sleep();
  42.         }
  43.         display.dispose();
  44.     }

    运行效果如下,只有选中第二列的单元格时,才会有右键菜单弹出: