动态创建实例对象[请多多指教]
本帖最后由 haiou327 于 2013-02-22 21:10:39 编辑 代码如下【水平有限请批评指正不胜感激】
unit DynamicCreateControlsPas;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure aBtnonClick(Sender: Tobject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure Tform1.aBtnonClick(Sender: Tobject); //事件过程定义
var
i: integer;
begin
for i := 1 to 5 do
begin
if ((Sender as TButton).Caption = 'btn' + inttostr(i)) or
((Sender as TButton).Caption = 'delphi' + inttostr(i))
then
ShowMessage((Sender as TButton).caption);
end;
end;
procedure TForm1.Button1Click(Sender: TObject); //创建对象实例
var
i: Integer;
begin
Button1.Tag := 0;
for i := 1 to 5 do
if not Assigned(TButton(FindComponent('btn' + inttostr(i)))) then
with TButton.Create(self) do
begin
Name := 'btn' + inttostr(i);
Button1.Tag := Button1.Tag + 80;
top := Button1.Tag;
left := 60;
Width := 80;
Height := 60;
Parent := Self;
onClick := aBtnonClick;
end;
end;
procedure TForm1.Button2Click(Sender: TObject); //实例赋值
var
aBtn: TButton;
i: integer;
begin
for i := 0 to 5 do
begin
aBtn := TButton(FindComponent('Btn' + inttostr(i)));
if Assigned(aBtn) then
aBtn.Caption := 'delphi' + inttostr(i);
end;
end;
procedure TForm1.FormDestroy(Sender: TObject); //释放对象实例
var
aBtn: TButton;
i: integer;
begin
for i := 0 to 5 do
begin
aBtn := TButton(FindComponent('Btn' + inttostr(i)));
if Assigned(aBtn) then
FreeAndNil(aBtn);
aBtn := TButton(FindComponent('delphi' + inttostr(i)));
if Assigned(aBtn) then
FreeAndNil(aBtn);
end;
end;
end.