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()));


		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]
			e.addListener(new MouseEvents.ClickListener(){
					public void click(MouseEvents.ClickEvent event) {
			picGrid.addComponent(e, column, row);


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
method and then act on the data in your listener by calling

Hi Teemu and Marko,

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


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