how to select one cell from SWT table

好久不见. 提交于 2021-02-18 11:47:09

问题


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 enter image description here

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!