Adding ClickHandler to div which contains many other widget
Asked Answered
G

3

12

It seems that Panel doesn't inherit from HasClickHandlers and I can't add a clickHandler to DivElement. Is there any way to add the clickHandler to a DIV?

EDIT: The reason I can't use Label as that the DIV I want to be clickable contains other DIV.

Glyco answered 29/11, 2010 at 11:34 Comment(1)
You can use the Label widget. It uses a div element and implements HasClickHandlers.Cocainism
C
39

By default, Panel doesnt 'sink' the onCLick event. That is, clicking on Panels doesnt actually result into a 'ClickEvent' and hence the handler isnt fired. To use click events with Panel (or for that matter any other Widget) you must first invoke sinkEvents() on it with the appropriate event bits.

For example:

SimplePanel p = new SimplePanel();
    p.sinkEvents(Event.ONCLICK);
    p.setTitle("Click me");
    p.setSize("600px", "600px");
    p.addHandler(new ClickHandler(){

        @Override
        public void onClick(ClickEvent event) {

            Window.alert("SimplePanel clicked!");

        }

    }, ClickEvent.getType());

The above piece of code first 'enables' click events for the SimplePanel using p.sinkEvents(Event.ONCLICK); and then goes on to add the standard ClickHandler onto it. Note that even though SimplePanel doesnt implement HasClickHandlers, you can always add a handler using the addHandler() method.

Calcic answered 29/11, 2010 at 11:47 Comment(2)
The sinkEvents solved my problem with SimplePanel that doesn't want to respond to clickEvents.Telles
Call addDomHandler instead, and then you don't need to sinkEvents.Detoxicate
M
11

Use the FocusPanel.

A simple panel that makes its contents focusable, and adds the ability to catch mouse and keyboard events.

Mainstay answered 29/11, 2010 at 12:2 Comment(2)
My DIV contains several other widgets. I can't use FocusPanel as it can only contain 1 widget.Glyco
That's not a problem: place your <div> containing several widgets inside the FocusPanel. Or is there a reason you can't do that?Mainstay
D
7
public class ClickableDiv extends FlowPanel implements HasClickHandlers {
    @Override
    public HandlerRegistration addClickHandler(ClickHandler handler) {
        return addDomHandler(handler, ClickEvent.getType());
    }
}

That should be all you need. addDomHandler will take care of "sinking" the event type for you.

Dailey answered 1/12, 2010 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.