How to create a gwt composite component with children using uibinder?
Asked Answered
F

2

18

I would like to create a component to decorate its children, such as:

mycomponent.ui.xml:

<g:FlowPanel addStyleNames="myStyle">
    <!-- how can i render children ? -->
</g:FlowPanel>

and then others can use:

<myapp:mycomponent>
    <g:Label>Decorated child</g:Label>
</myapp:mycomponent>

How can i render the children in uibinder? (or in Java, if i must)

Fluster answered 13/11, 2010 at 23:11 Comment(0)
G
33

Let MyComponent implement the HasWidgets interface for adding/removing child widgets.

The MyComponent.ui.xml looks as simple as

<g:FlowPanel ui:field="main" />

while you delegate the methods specified ind HasWidgets to the FlowPanel:

public class MyComponent extends Composite implements HasWidgets {

    private static MyComponentUiBinder uiBinder = GWT.create(MyComponentUiBinder.class);

    interface MyComponentUiBinder extends UiBinder<Widget, MyComponent> {}

    @UiField
    FlowPanel main;

    public MyComponent() {
        initWidget(uiBinder.createAndBindUi(this));
    }

    @Override
    public void add(Widget w) {
        main.add(w);
    }

    @Override
    public void clear() {
        main.clear();
    }

    @Override
    public Iterator<Widget> iterator() {
        return main.iterator();
    } 

    @Override
    public boolean remove(Widget w) {
        return main.remove(w);
    }
}

Calling

<M:MyComponent>
    <g:Label text="some text" />
</M:MyComponent>

will work this way.

Gurley answered 14/11, 2010 at 9:14 Comment(2)
Is there any performance hit for not Injecting the MyComponentUiBinder, instead of GWT.create-ing it?Raceway
AFAIK injecting is using GWT.create so I'd say noGurley
T
1

Using this XML:

<myapp:mycomponent>
    <g:Label>Decorated child</g:Label> 
</myapp:mycomponent>

will instantiate MyComponent and then call MyComponent.add(label). All you have to do is override .add(..) in your class MyComponent and apply any styles that you want to passed components.

Talmudist answered 13/11, 2010 at 23:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.