GWT – How to create a HTML Label
Jun 14th, 2010 | By admin | Category: GWTGWT provides a text-type label by default. You can set a text to a label but it is not possible to set a HTML to a Gwt label unless you do few changes.
Label myLabel = new Label();
myLabel.setText("This is my label");
myLabel.setHtml("This<br>is<br>my<br>label"); // compilation error
To achieve this , you can create your own customized label which extends com.google.gwt.user.client.ui.Widget. Have a look at the following code.
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Widget;
public class HTMLLabel extends Widget {
public HTMLLabel(){
this(null);
}
public HTMLLabel(String text)
{
setElement(DOM.createLabel());
if(text != null)
DOM.setInnerText(getElement(), text);
}
public String getText()
{
return DOM.getInnerText(getElement());
}
public void setHTML(String html){
DOM.setInnerHTML(getElement(), html);
}
public String getHTML(){
return DOM.getInnerHTML(getElement());
}
}
We have created a class (HtmlLabel) extending the Widget class provided by GWT. At the line 12 ,we created a label by using the DOM class inside the parametrized constructor . Now we should expose a method so that consumer of this class can set a HTML to the created Label element. At the line 22 , we exposed a method where we set the inner HTML of the created label element.
A consumer of the HTMLLabel can create the HTML label in the following way,
HTMLLabel htmlLabel = new HTMLLabel();
htmlLabel.setHTML("This<br>is<br>my<br>label");
The output is a HTML label. As we have extended the Widget class , you can easily associate any event handlers to the HTML label that supported with normal GWT label. You can also create a SPAN element in GWT by following the above methodology of extending Widget class. I will discuss the SPAN element creation in my future post.
