When we are dealing with OOP, we hate code duplication and love to use loops. As the same applies to gwt widgets as well, let see how we iterate over widgets. Consider a panel which have no. of widgets on it and at some point of time when we want to apply some style or action on it, as a programmer we prefer a loop rather than copy pasting. Let see now how we can iterate over all children attached to a parent widget.
If you are familiar with Java for-each loop, then it is quite easy to write as
Note: The iterator() method just gives the widgets added to the panel but not those added to its children panels. So you need to iterate again on the specific panel to get it children as well.
Next >> Why to use GWT UIBinder
Iterator < Widget > arrayOfWidgets = anyGWTPanel.iterator();
while (arrayOfWidgets.hasNext()) {
Widget ch = arrayOfWidgets.next();
//Play with ch
}
That is all to do to iterate all over the parent widget and in case of to find out specific type of widgets, for example to iterate over all buttons of a widget we can simply use instanceof key word and find out all the buttons. Iterator < Widget > arrayOfWidgets = anyGWTPanel.iterator();
while (arrayOfWidgets.hasNext()) {
Widget ch = arrayOfWidgets.next();
if (ch instanceof Button) {
//Do something (in your case make an arraylist of your objects)
}
}
Iterator() method is very handy when you are creating widgets in Java rather than UiBinder in GWT. If you are using UiBinder, then the task is very easy since we have very expertise in dealing with HTML.If you are familiar with Java for-each loop, then it is quite easy to write as
for (Widget ch : anyGWTPanel) {
if (ch instanceof Button) {
//Do something (in your case make an arraylist of your objects)
}
}
Note: The iterator() method just gives the widgets added to the panel but not those added to its children panels. So you need to iterate again on the specific panel to get it children as well.
Next >> Why to use GWT UIBinder
No comments:
Post a Comment