How to add click listener to Custom Notification in Vaadin?

22 views Asked by At

I want to add an outside click listener to detect when the user clicks outside of the component. I have created a CustomNotification.java which I want to close or hide when the user clicks outside of a CustomNotification instance. I applied several ways but still, it does not work.

public class CustomNotification extends Notification  implements ClickNotifier<Notification> {

    public CustomNotification(Component content) {
        Div contentWrapper = new Div(content);

        // Add the provided content to the dialog
        add(contentWrapper);
        
        setDuration(0); 
        setPosition(Position.BOTTOM_END); 
        
        // Add click listener
        ComponentUtil.addListener(this, ClickEvent.class, event -> {
            if (event.getSource() != null && event.getSource() != this) {
                this.close();
            }
        });
        
        addClickListener(event -> {
            if (event.getSource() != null && event.getSource() != this) {
                close();
            }
        });
        


        // Show the dialog
        open();
    }
    

    public static CustomNotification showNotification(Component content) {
        CustomNotification notification = new CustomNotification(content);              
        return notification;
    }
}

Usage of it.

public void openMessageDialog()
{
     customNotification = CustomNotification.showNotification(createDialogLayout());
     
     customNotification.addClickListener(event -> {
         if (event.getSource() != null && event.getSource() != customNotification) {
             customNotification.close();
         }
     });
     
     customNotification.getElement( ).addEventListener("click", e -> {
         if (e.getSource() != null && e.getSource() != customNotification.getElement( )) {
             customNotification.close();
         }
     });
}
0

There are 0 answers