Lifetime and use of FlexBox and FlexItem

Trying to understand the FlexBox demo code in Juce 5. I think we need a simpler demo to get us old dogs started.

Things I think I figured out but may be wrong:

  • Still need to call addAndMakeVisible( myComponent ); to ensure the parent component knows about the children
  • Parent component does not know to use FlexBox. You will likely want to use Component::resized() or ComponentListener::componentMovedOrResized() to make an explicit call to FlexBox::performLayout()

In my parent component, I have added several FlexBox members, and in my component constructor I setup all the boxes and items. But…should I instead instantiate the FlexBox I need on the stack within resized() and let it go out of scope at the end of the method? Does the flexbox and items need to persist beyond the scope of where I call performLayout()?

When I first started playing with this code I thought perhaps FlexBox and FlexItem might take ownership of the controls being passed in. Either way, please add a comment in FlexItem::FlexItem(Component &component) and FlexItem::associatedComponent that the lifetime of the FlexItem need not be the same as the component that it is adjusting.

If I want some components to be stacked horizontal, and others vertical, am I correct in thinking I need 3 flexboxes: one vertical, one horizontal, and one “master” to contain the first two flexboxes? Then within MyComponent::resized() I’d call master_flexbox.performLayout(), and it recursively does the layout?

1 Like

Don’t even bother with FlexBox items as members.

Just use 'em in your resized() call as local stack variables.

you are correct in thinking that if you want some columns and rows among your different component layouts, you gotta nest your flexBoxes:

FlexBox fb;
            fb.flexDirection = FlexBox::Direction::column;

            FlexBox upperComponents;
            upperComponents.flexDirection = FlexBox::Direction::row;

            FlexBox leftSide;
            leftSide.flexDirection = FlexBox::Direction::column;

            leftSide.items.add( FlexItem(titleBarModule).withFlex(0.15) ); //0.15
            leftSide.items.add( FlexItem(manuscriptModule).withFlex(1.0) ); //1.0

            FlexBox rightSide;
            rightSide.flexDirection = FlexBox::Direction::column;

            rightSide.items.add( FlexItem(chordNameModule).withFlex(0.5) ); //0.5
            rightSide.items.add( FlexItem(fretboardModule).withFlex(1.0) ); //1.0

            upperComponents.items.add( FlexItem(leftSide).withFlex(0.5));  //0.5
            upperComponents.items.add( FlexItem(rightSide).withFlex(1.0) ); //1.0

            fb.items.add( FlexItem(upperComponents).withFlex(1.0) ); //1.0
            fb.items.add( FlexItem(pianoRollModule).withFlex(0.35) ); //0.35


looks like this: