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


    为一个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.     }

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


 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值