用TObjectList实现的控件数组代码:
今天有人在一个群里反复在问Delphi里有没有类似于VB中控件数组的东西,不过感觉Delphi控件数组的管理稍显麻烦,所以写了如下的测试代码,大家可以看看:
{**
* 作者:网事如风
* 作用:用TObjectList实现的控件数组代码:
* 使用:
**}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Contnrs, Math;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
LabelList : TObjectList;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
Var
InsertLbl : TLabel;
I,RecCou : Integer;
begin
LabelList := TObjectList.Create();
RecCou := 8;
for I := 0 to RecCou - 1 do
begin
InsertLbl := TLabel.Create(nil);
InsertLbl.Parent := Self;
InsertLbl.Name := 'Test' + IntToStr(I);
InsertLbl.SetBounds( 20*(I+1), 20*(I+1), 20, 20);
InsertLbl.Color := IfThen( Odd(I), clred, ClYellow ); //颜色区分
LabelList.Add(InsertLbl);
InsertLbl := Nil;
end;
//使用
for I := 0 to LabelList.Count - 1 do
begin
TLabel(LabelList.Items[I]).Caption := IntToStr(I);
end;
//最后在FormClose的时候需要 : FreeAndNil(LabelList);
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FreeAndNil(LabelList);
end;
end.