Dynamic removal of UI component

Hi guys.

I hope this post finds you all well in these complicated Covid times.

It quite easy to find how to add dynamically (programmatically) UI Components to screens. However I didn’t find anything about their removal.

You can find here my case study: GitHub - ochoq/gantt

In the last app menu (a.k.a “dynamic screen testing”) I have 2 buttons that dynamically add (i) a Button and (ii) a Fragment to my screen.

In order to remove one of the Fragment added to the screen (theBox), each fragment holds a linkButton (remove) that fires a CloseEvent to the main screen.

From here : big question mark. The container is “theBox”. I feel that I should do something like theBox.remove(something) but no way to find out what the something should be.

Any help, idea or suggestion is more than welcome.

Plan B is to make the Fragment not visible but I really would prefer to remove it…

Thanks for your support and stay safe.

O.

Hello @olivier.choquet

The scrollBoxLayout component has some methods to remove child components:

  1. remove(Component childComponent)
  2. remove(Component... childComponents)
  3. removeAll()

You can get child component using scrollBoxLayout#getComponentNN(String id) or scrollBoxLayout#getComponentNN(int index) methods. The fragment id is defined in @UiController annotation.

Regards,
Gleb

Hello @durygin thanks for your support.

I tried to do what you’ve said.

  1. when I’m in the context of my screen and receive the event, I don’t how I can get the index of the fragment which sent the event … so I tried the solution with the Id.

  2. I created 4 fragments (dynamically) and was surprised to see that they all had the same Id, which was “gantt_Basicgragment”. I thought an Id was meant to be unique …

  3. Anyway, I implemented the following code in my Screen controller:

@Order(10)
@EventListener
public void onApplicationEvent(CloseEvent event) {
    theBox.remove(theBox.getComponentNN("gantt_Basicgragment"));
}

and whatever the Basicgragment the Close button of I click on, always the same 2 first items are removed.

I’ve updated the code in GIT, I probably miss something. What is your opinion ?

Cheers
O.

You can define a unique identifier for a fragment yourself, just like you did for buttons.

    public void onBtnAddPlusClick() {
        BasicFragment basic = fragments.create(this, BasicFragment.class);
        basic.getFragment().setId("frag" + cpt + "_dyn");
        basic.setIdRoom(cpt);
        cpt++;
        theBox.add(basic.getFragment());
    }

    @Order(10)
    @EventListener
    public void onApplicationEvent(CloseEvent event) {
        theBox.remove(theBox.getComponentNN("frag" + cpt + "_dyn"));
    }

Regards,
Gleb

It works!

Thank you very much.
In a nutshell I missed the .getFragment in:

basic.getFragment().setId(“frag” + cpt + “_dyn”);

And tried only:

basic.setId(“frag” + cpt + “_dyn”);

You helped me a lot.

O.