Adressing multiple, similar variables/objects in Delphi

Viewed 121

I am writing a program that uses many shapes and I need to create a procedure to turn them all white. The shapes in question are named SectorBorder1 to SectorBorder20.

Is there a way to adress the shapes like this or similarly?

SectorBorder[X].brush.color := ClWhite;
Inc(X);

...where X is the number (obviously), instead of having to do:

SectorBorder1.brush.color := ClWhite;
SectorBorder2.brush.color := ClWhite;
...
SectorBorder20.brush.color := ClWhite;

So basically being able to differentiate names through a variable. This is the only way I could think of describing it. (Sorry, could someone also maybe include a better discription?) Any advice would be greatly apreciated.

3 Answers

Use an array

private
  SectorBorders: array[1..20] of TShape;

procedure TMyForm.FormCreate(Sender: TObject):
begin
  SectorBorders[1] := SectorBorder1;
  ..
  SectorBorders[20] := SectorBorder20;
end;

procedure TMyForm.SetAllToWhite;
var
  X: Integer;
begin
  for X := Low(SectorBorders) to High(SectorBorders) do
    SectorBorders[X].Brush.Color := clWhite;
end;

As an alternative to an array you can use a List. If you use the TList from System.Generics.Containers you can easily pass through all elements of the list.

You use it like this:

interface

uses  System.Generics.Collections;   // you need this to get the TList, you also need your other refereces of course

  ...

  protected
    pShapes:  TList<TShape>;

  procedure TMyForm.FormCreate(Sender: TObject):
  var
    nLoop: Integer;
  begin
    Self.pShapes:=TList<TShape>.Create;
    nLoop:=0;
    while(nLoop<Self.ComponentCount) do
    begin
      if(Self.Components[nLoop] is TShape) then
        pList.Add(TShape(Self.Components[nLoop]));
      Inc(nLoop);
    end;
  end;

  procedure TMyForm.SetAllToWhite;
  var
    pShape:  TShape;
  begin
    for pShape in Self.pShapes do 
      pShape.Brush.Color := clWhite;
  end;

Choosing whether you want to use an array or a TList will be partially down to preference, but also down to what else you may want to do with the collection of TShapes and how they are managed within the object.

Related