这是一些可以完成您想要的操作的代码:
private static Map<TableColumn, Integer> mapping = new HashMap<TableColumn, Integer>();
public static void main(String[] args)
{
Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
Listener listener = new Listener()
{
@Override
public void handleEvent(Event arg0)
{
TableColumn column = (TableColumn) arg0.widget;
System.out.println(mapping.get(column));
}
};
Table table = new Table(shell, SWT.NONE);
table.setHeaderVisible(true);
for(int i = 0; i < 5; i++)
{
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText("Column " + i);
column.addListener(SWT.Selection, listener);
column.pack();
mapping.put(column, i);
}
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
Run Code Online (Sandbox Code Playgroud)
它基本上生成一个Map存储TableColumn作为键和位置作为值的存储。
Table或者,您可以迭代中的所有列Listener并将它们与单击的列进行比较。第一种方法(映射)速度更快,但使用更多内存,而第二种方法(迭代)速度较慢,但使用内存更少。