Add ClickListener to Composite

Ihave the following working Composite

public class IconButton extends Composite<FlexLayout> {
	private Button button;
	private Icon icon;
	public IconButton(String text, ICON_POSITION icp, VaadinIcon vaadinIcon) {
		int size = 50;
		int height = size + 4;

		button = new Button();
		button.setHeight("" + height + "px");

		icon = new Icon(vaadinIcon);
		icon.setSize("" + size / 2 + "px");

		if (icp == ICON_POSITION.TOP) {
			Div divText = new Div();
			divText.setText(text);
			button.getElement().appendChild(icon.getElement());
			button.getElement().appendChild(divText.getElement());
		}
		....
		getContent().add(button);
	}

	public enum ICON_POSITION {
		TOP, LEFT, BOTTOM;
	}
}

I use the Composite with:

IconButton iconButton = new IconButton("Top", ICON_POSITION.TOP, VaadinIcon.COG_O);

How can i add a ClickListener to iconButton

Something like:

iconButton.addCLickListener(e -> {
			WriteMailView detailView = new WriteMailView();
			detailView.open();
		});

I guess you want to add the listener to the encapsulated button. You can simply implement a method that sets the click listener to the button:

public class IconButton extends Composite<FlexLayout> {
	...
	public Registration addClickListener(ComponentEventListener<ClickEvent<Button>> listener) {
        return button.addClickListener(listener);
    }
	...
}

BTW, you can add an icon to a Button component using the Button.setIcon(Component) method.

Ohhh thanks.

one more question:

How can i define for Button.setIcon(Component)where the icon should be: top, left, right, bottom

On a regular Button, if there’s an icon, it is always on the left.

And if you want to add the listener to the whole composite not only the button within, I think your IconButton class needs to implement ClickNotifier<Composite>.

hans-georg gloeckler:
Ohhh thanks.

one more question:

How can i define for Button.setIcon(Component)where the icon should be: top, left, right, bottom

There is a method for left and right: button.setIconAfterText(true). AFAIK, there’s no API for top and bottom, though.