Adding different listeners in loop

Hi all,

i would like to know how to creat individual listeners for every loop step. In the example below i create some embedded pics which all contains a ClickListener. But at the moment it’s the same listener for every Embedded. How can I create individual listeners, e.g. by passing the parameter “i”? Target is to change/replacing bigPic by clicking one of the smallPics, but therefore I have to know which smallPic I actually have clicked.

     HorizontalLayout hl = new HorizontalLayout();

		Embedded bigPic = new Embedded("pic1",
				new FileResource(picFile1,this.getApplication()));

		hl.setWidth("100%");
		hl.addComponent(bigPic);
		addComponent(hl);

		GridLayout picGrid = new GridLayout();
		...

		int column = 0;
		int row = 0;
		for (int i = 0; i < picFileDir.length; i++) {
			...
			Embedded e = new Embedded(
					"smallPic" + i,
					new FileResource(smallPicFile[i]
),
							this.getApplication()));
			e.setWidth("200px");
			e.addListener(new MouseEvents.ClickListener(){
					public void click(MouseEvents.ClickEvent event) {
					System.out.println(i);					
				}
			});
			picGrid.addComponent(e, column, row);
			...
		}

Cheers
Benny

I think you can use event.getComponent() to access the component where the click occurred. Just cast it to Embedded.

I’m not quite sure what your problem is. You are creating a new instance of the listener for each embedded object there, although you could alternatively have just one instance of the listener and use the event.getComponent() to act on the specific Embedded instance.

You could also pass the Embedded as a parameter for the listener instance when you create it, but you can’t pass parameters to the anonymous class as it doesn’t have a constructor - you would need to use a local or other type of class for the listener. But you don’t need to do that as you can access (final) variables in the context where it was created (the method and the enclosing class), as you actually do in your code with the “i” variable.

And I might also add that you can set any data to your Embedded component instance via the
setData
method and then act on the data in your listener by calling
getData
.

Hi Teemu and Marko,

many thanks to both of you, that information helps me a lot!


e.setData(i);

Embedded e = (Embedded) event.getComponent();
System.out.println((Integer) e.getData());