Get item in SWT list on Mouse Up

I wanted to know if its possible to get an item in the list using the mouse? I searched the web and found many examples for SWT table using X and Y coordinates, but none of them used a list. I am mainly working on implementing a list where the order of the items can be changed by drag and drop. To do this, I need to be able to get the element below the drop location so that I can swap that element with the dragged item.

+3


source to share


1 answer


List#getItemHeight()

returns the height of the area occupied by one element. With this information, getTopIndex()

you should be able to compute the element at the given x and y coordinates.

list.addListener( SWT.MouseDown, new Listener() {
  @Override
  public void handleEvent( Event event ) {
    int itemTop = 0;
    for( int i = 0; i < list.getItemCount(); i++ ) {
      if( event.y >= itemTop && event.y <= itemTop + list.getItemHeight() ) {
        System.out.println( "Click on item " + list.getItem( list.getTopIndex()  + i ) );
      }
      itemTop += list.getItemHeight();
    }
  }
} );

      



Alternatively, you can use a single column table with setHeaderVisible( false )

to emulate a list widget. The table provides better drag and drop support out of the box.

+3


source







All Articles