GWT - How to layout components horizontally in a FlowPanel?
Asked Answered
C

2

10

The GWT documentation recommends using a FlowPanel (float: left set on its children) as a replacement for the HorizontalPanel to layout components. But how to do this?

Chilson answered 15/2, 2011 at 15:32 Comment(0)
L
16

Says so right in the docs:

and to use the float: left; CSS property on its children.

How to set a style on GWT widget:

widget.getElement().getStyle().setProperty("float", "left");
Legerdemain answered 15/2, 2011 at 15:40 Comment(3)
Preferable use widget.getElement().getStyle().setFloat(Float.LEFT);Expend
Can't I use a CSS class for that?Chilson
You absolutely can. This was just the inline way to do it per object. widget.setStyleName("cssClass");Legerdemain
K
5

To avoid using HorizontalPanel I use the following code where possible:

FlowPanel panel = new FlowPanel() {
    @Override
    public void add(Widget child) {
        super.add(child);
        child.getElement().getStyle().setDisplay(Display.INLINE_BLOCK);
    }
};

And using an UIBinder I do something like:

<ui:UiBinder ...>
    <ui:style>
        .vertical > * {
            display: inline-block;
        }
    </ui:style>

    <g:FlowPanel styleName="{style.vertical}">
        ...
    </g:FlowPanel>
</ui:UiBinder>

Or you can substitute all HorizontalPanel references by this HorizontalFlowPanel class:

public class HorizontalFlowPanel extends FlowPanel {
    private static final String BASIC_CLASS_NAME = "___" + Math.abs(Random.nextInt());
    private static final String HORIZONTAL_CLASS_NAME = BASIC_CLASS_NAME + "_H_";
    private static final String VERTICAL_CLASS_NAME = BASIC_CLASS_NAME + "_V_";

    static {
        newCssClass(HORIZONTAL_CLASS_NAME + " > *", "display: inline-block; vertical-align: top;");
        newCssClass(VERTICAL_CLASS_NAME + " > *", "display: block;");
    }

    private static int count = 0;

    private final String myClassName = BASIC_CLASS_NAME + count++;

    public HorizontalFlowPanel() {
        super();
        setStylePrimaryName(HORIZONTAL_CLASS_NAME + " " + myClassName);
    }

    public void setSpacing(int spacing) {
        newCssClass(myClassName + " > *", "margin-bottom: " + spacing + "px; margin-right: " + spacing + "px;");
    }

    public void setPadding(int padding) {
        newCssClass(myClassName, "padding: " + padding + "px;");
    }

    public static void newCssClass(String className, String content) {
        StringBuilder builder = new StringBuilder();
        builder.append("." + className + " { " + content + " }\n");

        Element style = DOM.createElement("style");
        style.setAttribute("type", "text/css");
        style.setInnerHTML(builder.toString());

        Document.get().getHead().appendChild(style);
    }
}
Kopeck answered 31/12, 2015 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.