问题
table.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
if(table.getSelectionIndex() != -1)
{
System.out.println(table.getSelectionIndex());
TableItem item = table.getItem(table.getSelectionIndex());
System.out.println(item.toString());
}
else
{}
}
});
when i click on any cell in my table, only the first cell of that row is selected and returned and not exactly that cell
please tell me how can i select and get item from exactly that cell which i select
please see the image
i have selected 3rd column but it returned the TableItem of first column
回答1:
I encountered the same problem before, and this is how I solved it:
First, you should make the table SWT.FULL_SELECTION`;
Then, you have to get the selected cell by reading the mouse position (because the basic swt table does not provide listeners to get selected cell; select a item is possible). Here is the code:
table.addListener(SWT.MouseDown, new Listener(){
public void handleEvent(Event event){
Point pt = new Point(event.x, event.y);
TableItem item = table.getItem(pt);
if(item != null) {
for (int col = 0; col < table.getColumnCount(); col++) {
Rectangle rect = item.getBounds(col);
if (rect.contains(pt)) {
System.out.println("item clicked.");
System.out.println("column is " + col);
}
}
}
}
});
回答2:
I was facing a similar problem with nebula grid and found out that you have to enable cell selection on the table object. Here is my code line:
tableViewer.getGrid().setCellSelectionEnabled(true);
Perhaps it you could try to replace getGrid() by getTable(). You will not need to implement the selection listener for this.
来源:https://stackoverflow.com/questions/11828053/how-to-select-one-cell-from-swt-table