Search code examples
codenameone

How to set a button expands to a whole the space or shrink to minimal width in a tablelayout?


I don't know how to set a button(or textfield) to expand to the whole space or shrink to minimal width of the button in a table-layout. For example:

    TableLayout tl = new TableLayout(1,2);
    Container Cnt = new Container(tl);
    add(Cnt);
    Button searchBtn = new Button("Expand or Shrink");
    Cnt.add(tl.createConstraint().widthPercentage(80),searchBtn);

Sometimes searchBtn would expand to the whole space(80 percent of container's width), but others would shrink to the minimum width of searchBtn in a table-layout.

How do I expand or shrink a button in a table-layout as I wish?

And the expanding and shrinking rules of a button for in a BoxLayout.


Solution

  • The default behavior of a table layout is fill. If you add the button directly it will take up the 80 percent:

    Cnt.add(tl.cc().wp(80), searchBtn);
    

    If you need it to be in a container make sure not to use something like FlowLayout which grants it preferred size. Use something like the center of a border layout which grants the available size.

    To make the button take the preferred size you can use a couple of other approaches. There are other constraints available as explained in the javadocs. There's also the common trick of nesting as you mentioned in the comment. E.g. for nesting:

    Cnt.add(tl.cc().wp(80), FlowLayout.center(searchBtn));
    

    Notice you can use other constraints in the flow layout to impact the alignment.

    The second approach is to use the layout constraints:

    Cnt.add(tl.cc().wp(80).ha(CENTER), searchBtn);
    

    See: https://www.codenameone.com/javadoc/com/codename1/ui/table/TableLayout.Constraint.html#setHorizontalAlign-int-