开发者

How to add a GWT click listener to an Image?

I want to click on an image and therefore want to register (e.g.) a ClickHandler. The image I get from a ClientResource. This works so far to set the image into a table cell:

MyResources.INSTANCE.css().ensureInjected();
Image colorImage = new Image( MyResources.INSTANCE.colorImage() );
Element colorImageElement = colorImage.getElement();

colorImage.addClickHandler(new ClickHandler() {
 public void onClick(ClickEvent event) {
  System.out.println( event );
 }
} );

TableElement table = Document.get().createTableElement();
TableRowElement headRow = table.insertRow(-1);
headRow.insertCell(-1).appendChild( colorImageElement );

RootPanel.get().getElement().appendChild( table );

How can I add a listener to the icon? I tried ClickHandler and to put the image on a PushButton and get the Element from this PushButton but all don't work.

But mind, if I add the widget (Image is a Widget) to a panel it works!

RootPanel.get().add( colorImage );

开发者_开发知识库But I am not working with widgets here but with the Element. So the handler disappears and that's the point I don't get how to preserve this added handler information.

In the end I would like to build a table with different rows where I can click on the icon I get a popup menu and thereby change the colour of the row.


You should be able to just add a ClickHandler (or a MouseDownHandler if that fits your needs better).

Like this:

colorImage.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                // Do something....
            }
        });


Don't unwrap your widget and append only the DOM elements. The Widget class allows your code to refer to both elements and events at the same time, and deals with possible memory leaks, as well as grouping your code in logical ways.

This might make sense for other frameworks, but in GWT you almost always want to work with the Widgets directly, adding them together, then appending them to the RootPanel.

If you really want to use a html table to build this up, look at the com.google.gwt.user.client.ui.HTMLTable subclasses, com.google.gwt.user.client.ui.Grid and com.google.gwt.user.client.ui.FlexTable. This probably should never be necessary, unless you are adding multiple items to the table - when trying to specify layouts, use actual layout classes.


did you tried to add image.sinkEvents( Event.ONCLICK | Event.MOUSEEVENTS )?


The image has to be inside a focus widget. I don't know why that is, but somewhere the events don't get propagated right and the DOM events don't fire.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜