6.3. TitlePanel
TitlePanel
displays the symbol name on selection by the user and uses
a SimplePanel
and Label
.
Why a separate widget when a Label is suffice, and reason for this is
with more and more widgets added to Snapshot events handling becomes
complicated and with a separate widget we can wire events much more
elegantly. Hence TitlePanel is pulled out as a separate widget with
TitlePanel.ui.xml
and TitlePanel.java
.
Snapshot uses TitlePanel in Snapshot.ui.xml
which earlier used a Label
as placeholder for this widget.
in.fins.client.content/Snapshot.ui.xml
<g:LayoutPanel ui:field="layout">
<g:layer left='60%' width='40%' top='1%' height='5%'>
<!-- AutoSuggest -->
</g:layer>
<g:layer left='2%' width='50%' top='1%' height='5%'>
<f:TitlePanel />
</g:layer>
Wire TitlePanel and AutoSuggest
TitlePanel
has to listen to AutoSuggest
and display the symbol name
when user selects one. Instead of traditional event and handler method
we use GWT EventBus infrastructure to avoid direct couple between these
widgets. AutoSuggest fires a NameEvent
to EventBus which in turn
dispatches the event to TitlePanel. GWT EventBus mechanism is explained
in detail in EventBus. The NameEvent.java
defines NameEvent and NameHandler, and NameEvent holds
the name selected by the user. Wire AutoSuggest and TitlePanel as
follows.
First make TitlePanel as a handler of NameEvent.
in.fins.client.widget/TitlePanel.java
public class TitlePanel extends Composite implements NameHandler{
...
@Override
public void onNameChange(NameEvent nameEvent) {
log.fine("NameEvent " + nameEvent.getName());
label.setText(nameEvent.getName());
}
Next, register TitlePanel as a handler for NameEvent with EventBus.
in.fins.client.content/Snapshot.java
@UiField
TitlePanel titlePanel;
public Snapshot() {
initWidget(binder.createAndBindUi(this));
autoSuggest.requestFocus();
EventBus.get().addHandler(NameEvent.TYPE, titlePanel);
Finally, on selection fire NameEvent from AutoSuggest.
in.fins.client.widget/AutoSuggest.java
@UiHandler("suggestBox")
public void handleSelection(SelectionEvent<SuggestOracle.Suggestion> s) {
log.fine("Selection : " + suggestBox.getText());
EventBus.get().fireEvent(
new NameEvent(suggestBox.getText()));
suggestBox.setText("");
}
In Snapshot.java
, we got hold of TitlePanel through @UiField
to add
the handler, and this is adequate as long as the number of widgets are
few. Snapshot ends up with more than a dozen of widget and with so many
UI fields it soon results in untidy code. Instead, we may use
@UiFactory
which is a convenient way to create the multiple instances
of widgets. In the next section, we are going to look at different ways
of widget initialization in UiBinder.