euraad
euraad

Reputation: 2856

Is it possible to get a component from layout in Vaadin by labeling it?

I have a question. Is it possible to get a component from a layout in Vaadin by labeling it with a specific name or something?

Asume that we have this code.

    NumberField totalSamples = new NumberField();
    totalSamples.setValue(0d);
    totalSamples.setEnabled(false);
    Label label = new Label("Total samples:");
    Button start = new Button("Start");
    row = new HorizontalLayout();
    row.add(start, label, totalSamples);
    layout.add(row);

If I want to get the label object from layout and first need to get the row object and if I don't know the index of all of them. Is there some way to get these objects by setting a specific number or name to them?

    Button start = layout.getComponentAt(index)

Upvotes: 2

Views: 221

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 339372

Use a collection.

Vaadin objects are simply Java objects. So, as you instantiate the widgets, add them to a List or other collection that fits your needs.

Your collection can be stored as a member variable on your outer layout class.

In your specific case of needing to track dynamically-created rows where each has three widgets across, create a class. That class should extend HorizontalLayout. The class would have three member variables, each named so you can later access them individually.

class Row extends HorizontalLayout {

    NumberField totalSamples ;
    Label label ;
    Button start ;

    // Constructor
    public Row ( … ) {
        totalSamples = … ;
        label = … ;
        start = … ;
        this.add( label , totalSamples , start ) ;
    }

}

You could add other member variables to this Row class besides Vaadin widgets. If each row represents a particular product made by your company, the add a productId field. Or perhaps you you want to track each row individually for logging, debugging, or audit trail. If so, add a UUID field to the class.

That Row class could be nested within the outer layout class, as you’ll not need it anywhere else in your app.

On your outer layout, instantiate, collect, and place the rows.

Upvotes: 2

Related Questions