Changing properties

Posted by Marc M

I'm new to Delphi (1 week) and I must say it is great!
I created an app that needs to change a label color and a shape color when a buton is pressed. Below is the code. Is this the coreect way to do it. It seems convoluted that I have to use labels to associate everything. Thanks for the advice!

procedure TForm2.bSwClick(Sender: TObject);
var e: TButton;
i: integer;
begin
e := Sender as TButton;
for i := 0 to componentcount - 1 do
begin
if components[i] is TLabel then
if components[i].tag = e.tag then
if Tlabel(components[i]).Font.Color = clBlack then
Tlabel(components[i]).Font.Color := clRed
else
begin
Tlabel(components[i]).Font.Color := clBlack;
end;
begin
if components[i] is TShape then
if Tshape(components[i]).tag = e.tag then
Tshape(components[i]).Visible := not (Tshape(components[i]).Visible);
end;
end;
end;

Answer by Eric

Your code is correct, you can't simplify it if you want to change properties of several components, each with their own button, but still using a common onclick-event-handler.

Of course, the code becomes much simpler if you have 1 button per label/shape pair:

procedure TForm1.Button1Click(Sender: TObject);
begin
  if Label1.Font.Color = clBlack then 
    Label1.Font.Color := clRed
  else 
    Label1.Font.Color := clBlack;
  Shape1.Visible := not Shape1.Visible;
end;