Nemin
Nemin

Reputation: 2027

Get the item in the SWT list on Mouse Up

I wanted to know if its possible to get the item in the list on mouse up? I searched online and found many examples for SWT table using the X and the Y coordinate but none using a list. What I am basically doing is implementing a list in which the order of the items can be changed by drag and drop. For this I need to be able to get the item under the drop location so that I can swap that item with the dragged item.

Upvotes: 3

Views: 587

Answers (1)

Rüdiger Herrmann
Rüdiger Herrmann

Reputation: 20985

List#getItemHeight() returns the height of the area one item occupies. With that information and getTopIndex()you should be able to compute the item at a given x and y coordinate.

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 could use a single-columned table with setHeaderVisible( false ) to emulate a list widget. The table provides better drag and drop support out of the box.

Upvotes: 3

Related Questions