Basic OwnedArray Questions


i have 20 Labels (called for testing label1, label2… label20).
And i want to access these Labels by numbers.
As idea in a For-Loop, to write for every Label the name “MYLABEL”, instead of calling each label one by one in a line of code and set the name.

My idea is to do it in an OwnedArray of Labels. Could that work?
As i understood OwnedArrays, i can make an Array of Pointers, each Pointer points to a Specific label.

For example could i:

and that would change the name of Label 6 to the given String?

That would be great.


OwnedArray<Label> labels;

for (auto i = 0; i < 20; ++i)
   labels.add(new Label({}, "Label Number " + String(i)));

for (auto * label: labels)

You can do things like this …

label[num]->setText("new label text", dontSendNotification);

Note that as OwnedArray is an array of pointers you need to use the -> operator not the . operator to access the methods.

Bear in mind the label constructor takes the label text as the second parameter:

Label (const String &componentName=String(), const String &labelText=String())
1 Like

Just needed such an example to understand the working of the OwnedArray. Documentation has no real Examples, and i am very new to c++ and Juce, so examples help me alot!!

thought i need to create first 20 Labels.
And then add pointers to each of them from the array.

Thanks, gonna get back here if i stuck on further operations!!



1 Like

Since OwnedArray::add() returns the added pointer, you can even reduce to one loop:

OwnedArray<Label> labels;

for (auto i = 0; i < 20; ++i)
    addAndMakeVisible (labels.add (new Label({}, "Label Number " + String(i))));

Well I never notice that it did that.

Code here often looks like

for (auto i = 0; i < 20; ++i)
   auto newLabel = new Label({}, "Label Number " + String(i));

It just saves one variable. But your version is surely easier to understand. And I am pretty sure, the produced binary will be identical.
Plus your first example shows nicely the new way how to iterate a container…
Just posted it as a gimmick…

I heard that the code goes faster if the source file has fewer characters.

Only if you use counterclockwise twisted AC cables, that take account for the earth rotation in the northern hemisphere…


That’s why we should use tabs instead :troll:


You shouldn’t even jokingly say anything like that when newbies are around.


Newbies don’t go away, they will always be around. Lighten up. :slight_smile:

1 Like