如果你读过李维先生的书,应该可以找到这个例子:www.inprises.com 上有这本书的源码。
安装以后默认在:C:/Program Files/MDelphi4(2)/Chap09/DynamicCheckBox
unit fDynamicCheckBoxMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
btnCreateCheckBoxes: TBitBtn;
btnSaveCheckBoxes: TBitBtn;
btnloadCheckBoxes: TBitBtn;
btnOK: TBitBtn;
procedure btnOKClick(Sender: TObject);
procedure btnCreateCheckBoxesClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnSaveCheckBoxesClick(Sender: TObject);
procedure btnloadCheckBoxesClick(Sender: TObject);
private
{ Private declarations }
aList : TList;
procedure DeleteCheckBoxes;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.btnOKClick(Sender: TObject);
begin
Close;
end;
procedure TForm1.btnCreateCheckBoxesClick(Sender: TObject);
const
OFFSET : Integer = 40;
var
iCount, yPos : Integer;
aCheckBox : TCheckBox;
begin
yPos := 40;
for iCount := 1 to 5 do
begin
aCheckBox := TCheckBox.Create(Self);
aCheckBox.Parent := GroupBox1;
aCheckBox.Left := 9;
aCheckBox.Top := yPos;
aCheckBox.Width := 300;
aCheckBox.Caption := 'CheckBox北?じン' + IntToStr(iCount);
yPos := yPos + OFFSET;
aList.Add(aCheckBox);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
aList := Tlist.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
DeleteCheckBoxes;
aList.Free;
end;
procedure TForm1.btnSaveCheckBoxesClick(Sender: TObject);
var
fSaveStream : TMemoryStream;
iCount : Integer;
aCheckBox : TCheckBox;
begin
try
fSaveStream := TMemoryStream.Create;
for iCount := 0 to aList.Count - 1 do
begin
aCheckBox := aList.Items[iCount];
fSaveStream.WriteComponent(aCheckBox);
end;
fSaveStream.SaveToFile('sCksbo9.cps');
finally
fSaveStream.Free;
end;
end;
procedure TForm1.btnloadCheckBoxesClick(Sender: TObject);
var
fSaveStream : TMemoryStream;
iCount : Integer;
aCheckBox : TCheckBox;
begin
DeleteCheckBoxes;
Classes.RegisterClasses([TCheckBox]);
try
fSaveStream := TMemoryStream.Create;
fSaveStream.LoadFromFile('sCksbo9.cps');
for iCount := 0 to 4 do
begin
aCheckBox := fSaveStream.ReadComponent(nil) as TCheckBox;
aCheckBox.Parent := GroupBox1;
aCheckBox.Left := 90;
aCheckBox.Font.Color := clRed;
aList.Add(aCheckBox);
end;
finally
fSaveStream.Free;
end;
end;
procedure TForm1.DeleteCheckBoxes;
var
iCount : Integer;
aCheckBox : TCheckBox;
begin
for iCount := aList.Count - 1 downto 0 do
begin
aCheckBox := aList.Items[iCount];
aCheckBox.Free;
aList.Delete(iCount);
end;
end;
end.