为一个Table添加菜单后,当右击该Table的某一行,即可弹出定义好的菜单,这个不难做到。今天碰到一需求:需要针对Table的某一列(Column)的单元格添加右键菜单,也即:只有在右键单击某一列的单元格时,才在被选中的单元格上显示出该右键菜单。为实现这一需求,我们需要使用org.eclipse.swt.custom包中的TableCursor类,示例代码如下:
- public static void main(String[] args) {
- Display display = new Display();
- Shell shell = new Shell(display);
- shell.setLayout(new GridLayout());
- // create a a table with 3 columns and fill with data
- final Table table = new Table(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE);
- table.setLayoutData(new GridData(GridData.FILL_BOTH));
- int columnSize = 3;
- TableColumn column;
- for (int i = 0; i < columnSize; i++) {
- column = new TableColumn(table, SWT.NONE);
- column.setWidth(100);
- column.setText("Column" + i);
- column.pack();
- }
- table.setHeaderVisible(true);
- for (int i = 0; i < 10; i++) {
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(new String[] { "cell" + i + "0", "cell" + i + "1", "cell" + i + "2" });
- }
- final TableCursor cursor = new TableCursor(table, SWT.NONE);
- cursor.setBackground(table.getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION));
- cursor.setForeground(table.getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT));
- cursor.setLayout(new FillLayout());
- final Menu menu = new Menu(table);
- MenuItem item = new MenuItem(menu, SWT.PUSH);
- item.setText("Hello Menu");
- cursor.addSelectionListener(new SelectionAdapter() {
- public void widgetSelected(SelectionEvent e) {
- int column = cursor.getColumn();
- if (column == 1) {
- table.setMenu(menu);
- } else {
- table.setMenu(null);
- }
- }
- });
- shell.open();
- while (!shell.isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
- display.dispose();
- }
运行效果如下,只有选中第二列的单元格时,才会有右键菜单弹出: