Search code examples
javavaadinobserver-patternvaadin7

Create listener for CustomComponent in Vaadin


I'm trying to create a CustomComponent in vaadin 7. The component has a VerticalLayout set in its setCompositionRoot() method and some Labels and other layouts are set within that VerticalLayout. Implementing my custom component in the main view class I would like to be able to handle clicks on my custom component, meaning the VerticalLayout as the composition root element:

MyCustomComponent component = new MyCustomComponent();
component.addOnClickListener(listener);

But there is no method like addOnClickListener available. How can I implement that functionality? I know that I can handle a click on a layout with the LayoutClickListener within the custom component, but is there also a way that I can set the listener, where the component is declared, e.g. in the main view class (similar to the code snippet above)?


Solution

  • create your own method like you named addOnClickListener, that take as a parameter LayoutClickListener . Inside the implementation of addOnClickListener you add the listener to your layout. Example:

    component.addOnClickListener(new LayoutClickListener() {
    
                @Override
                public void layoutClick(LayoutClickEvent event) {
                    // TODO Auto-generated method stub
    
                }
            });
    

    and the implementation of component.addOnClickListener:

    public void addOnClickListener(LayoutClickListener listener){
        yourVerticalLayout.addLayoutClickListener(listener);
    }