getComponents()

Hi. i have something like this:

VertticalLayout1
	VerticalLayout2
		HorizontalLayout
			Label

and want to get Label by VerticalLayout1. if i use getcomponent(0) i get VerticalLayout2 but how to get Label?

Hi, I use here Vaadin 12.
So if you really really have to do it then just cast the components that you received by getComponent method.

    Component component = verticalLayout1.getComponentAt(0);
    VerticalLayout yourVerticalLayout2 = (VerticalLayout) component;
    HorizontalLayout yourHorizontalLayout = (HorizontalLayout) yourVerticalLayout2.getComponentAt(0);
    Label yourLabel = (Label) yourHorizontalLayout.getComponentAt(0);

Of course the best case is that you just create the local variable or field for your Label while creating it. But if you don’t have this possibility then do it as I showed you. You should also check if you can cast the component to the other one by:

if (component instanceof HorizontaLayout)

Otherwise: you can get ClassCastException if the structure is not exactly as you assumed.

Best,
Piotr

Thank you so much) I knew this method but hoped that we could do it differently)

I used javaFX before vaadin and there we could call getComponents() several times. For exp: in his case in javaFX we could do VerticalLayout.getChildren().getChildren().getChildren()

It was very comfortably))

Actually there is something like that but you should be aware that there is a lot of places where the exception may come from. If you are sure about the structure then the code below should work as well. However I wouldn’t recommend that.

    component.getChildren().findFirst().get().getChildren().findFirst().get()...

Thank you, Piotr.

But here is no any getChildren() methods only getComponent().

It depends on the version of Vaadin you use. You clearly don’t use the newest Vaadin. Best, Piotr