-1

I have a lot of labels in my form and I have to change the color to all of them, so I thought to use a for loop + the FindComponent method.

procedure TForm1.RadioButton1Click(Sender: TObject);
var i:shortint;
begin
for i:=16 to 27 do
  begin
   TLabel(FindComponent('Label'+IntToStr(i)).Font.Color:=clYellow);
  end;
 Label85.Font.Color:=clYellow;
 Label104.Font.Color:=clYellow;
end;

I'm using lazarus and I have this kind of error: identifier idents no member "Font" . By the way as you can see Label104.Font.Color:=clYellow; works (for example). How could I solve this?

4

2 回答 2

6
TLabel(FindComponent('Label'+IntToStr(i)).Font.Color:=clYellow);

显然应该读

TLabel(FindComponent('Label'+IntToStr(i))).Font.Color:=clYellow;
于 2013-08-08T20:06:12.353 回答
5

您的代码甚至不应该编译,因为您的括号不合适:

TLabel(FindComponent('Label'+IntToStr(i)).Font.Color:=clYellow);

之后的右括号clYellow应该在 之后IntToStr(i))和之前的其他两个.Font

TLabel(FindComponent('Label'+IntToStr(i))).Font.Color:=clYellow;

不过,您的代码风险很大。它假设它会找到标签(如果标签在未来被重命名或删除,它可能会失败)。在使用以下结果之前先检查会更安全FindComponent

procedure TForm1.RadioButton1Click(Sender: TObject);
var 
  i: Integer;
  TempComp: TComponent;
begin
  for i := 16 to 27 do
    begin
     TempComp := FindComponent('Label' + IntToStr(i));
     if TempComp <> nil then
       (TempComp as TLabel).Font.Color:=clYellow;
    end;
  Label85.Font.Color :=clYellow;
  Label104.Font.Color :=clYellow;
end;

(最后两行是安全的,因为编译器会告诉您这些标签是否被重命名或删除;在这种TLabel(FindComponent())情况下它不能这样做,因为它无法在编译时告诉您将访问哪些标签。)

于 2013-08-08T20:08:54.453 回答