Hi EveryOne , today we will be working on creating our own widgets in Gwt.actually there are 3 ways creating our own widgets in gwt .
1.by extending a Class called “Composite”
2. by extending any Widget class like “button” , “label”
3.by extending Widget class.
Today we will see how we can create a new widget by using these 3 types
1.By extending Composite widget
When we extends a Composite class to create a new widget , we need to call the initWidget(widget) method compulsory in their constructors as it initializes the widget.
Lets take a look at the sample example of creating a new widget which contains a button and a label set to a horizontalPanel.
public class SampleWidget extends Composite {
private Button smallButton;
private Label myLabel;
private HorizontalPanel panel;
public SampleWidget() {
panel=new HorizontalPanel();
panel.setBorderWidth(1);
smallButton=new Button("Sample Button",new ClickListener() {
public void onClick(Widget sender) {
Window.alert("You Clicked On Sample Button");
}
});
myLabel=new Label("Sample Label");
panel.add(myLabel);
panel.add(smallButton);
initWidget(panel);
}
}
In the above code , I just created a button and a label and added them to the horizontalpanel.i called the initWidget(panel) in order to initialize the panel.
Now we can use the widget like ,
SampleWidget widget=new SampleWidget();
U can create a new as you like with different widgets in it.
2. the second way of creating a new widget by extending any widget class like
Button , Label e.t.c . below is the code snippet where I extended the Button class.
public class SampleWidget extends Button {
SampleWidget(){
this.setText("Sample Widget");
this.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
Window.alert("You Clicked On The Sample Widget");
}
});
}
}
U can use this similarly as above
SampleWidget widget=new SampleWidget();
3. the third one is by extending Widget class.
public class SampleWidget extends Widget {
SampleWidget(){
this.setElement(DOM.createButton());
getElement().setInnerHTML("Sample Widget");
}
}
In this class , I have extended the widget class.in order to create a button element DOM.createButton() and added by using the method setElement() method, I have used DOM(document Object Model) in order to work.
This setElement(DOM.createButton()); method wraps a button element
I set the text for the button by using getElement().setInnerHtml(“SampleWidget”);
In next article we will discuss of creating our own widget with event listeners.
No comments :
Post a Comment