[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[news.eclipse.tools] Re: Which Column in a table is selected


While you can not get the "selected" column directly, you can can get at it in a round about way.

The selection event does not give you mouse coordinates because it is possible to perform selection without using the mouse (e.g. with the up/down arrows).  However, if you are only interested in the cases where selection is done by the mouse, you can get the mouse coordinates from the Mouse event and then translate those coordinates into a column index.  In the following example, I listen for the MouseDown event and figure out what column I clicked in by checking the bounds of each cell in the selected row to see if it contains the mouse coordinates.  I print out the column name for the selected column.:

public static void main (String [] args) {
        Display display = new Display ();
        Shell shell = new Shell (display);
        final Table table = new Table(shell, SWT.MULTI | SWT.FULL_SELECTION | SWT.BORDER);
        table.setHeaderVisible(true);
        table.setBounds(10, 10, 200, 200);
        for (int i = 0; i < 5; i++) {
                TableColumn column = new TableColumn(table, SWT.NONE);
                column.setText("column "+i);
                column.setWidth(75);
        }
        for (int i = 0; i < 100; i++) {
                TableItem row = new TableItem(table, SWT.NONE);
                for (int j = 0; j < 5; j++) {
                        row.setText(j, "row "+i+" - "+j);
                }
        }
        table.addListener(SWT.MouseDown, new Listener() {
                public void handleEvent(Event e) {
                        TableItem[] selection = table.getSelection();
                        if (selection.length ==0) return;
                        TableColumn[] columns = table.getColumns();
                        for (int i = 0; i < columns.length; i++) {
                                Rectangle bounds = selection[0].getBounds(i);
                                if (bounds.contains(e.x, bounds.y)) { // because we don't care about the y direction,
                                                                        // using bounds.y simplifies the multi select case
                                        System.out.println("Clicked in "+columns[i].getText());
                                        break;
                                }
                        }
                       
                }
        });
        shell.open ();
        while (!shell.isDisposed ()) {
                if (!display.readAndDispatch ()) display.sleep ();
        }
        display.dispose ();
}