比如procedure TForm1.Button1Click(Sender: TObject);
var
i:Integer;
lbl: TLabel;
begin
for i:=1 to 3 do
begin
lbl:= TLabel.Create(Application);
lbl.Parent := Self;
lbl.Caption := 'lbl'+IntToStr(i);
lbl.Top := 175;
lbl.Height := 75;
lbl.Width :=75 ;
lbl.Left := i* lbl.Width + 10;
end;
动态生成了3个控件,但怎么在同一个事件中(再点一下这个按钮)就又把它们全都删除(也就是释放吧!)呢?
--------------------------------------------------------
用一个数组来存这些动态生成的指针,以便以后释放。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
IsLableCreated:Boolean;
Labels:array[0..2] of TLabel;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
if not IsLableCreated then
begin
for I := 0 to 2 do
begin
Labels[I]:=TLabel.Create(Self);
with Labels[I] do
begin
Parent:=self;
Caption := 'Label ' + IntToStr(I);
Top := 175;
Width := 75;
Height :=75;
Left := I*Width +10;
end;
IsLableCreated := True;
end;
end
else
begin
for I := 0 to 2 do
Labels[I].Free;
IsLableCreated := False;
end;
end;
end.
----------------------------------------------------------
设置一个全局布尔变量 点一下改变其值
var
bnil: boolean=false;
procedure TForm1.Button1Click(Sender: TObject);
begin
if bnil = false then
//生成控件
bnil := true;//改变值
else //即bnil = true;
//释放
end;