Beranda > Delphi > Create a number of components runtime

Create a number of components runtime

Question/Problem/Abstract:

How can I create a given number of components runtime, without declaring them first? Next, how can I write event handlers to them?

Answer:

Well, the answer is not as hard as it may seem to.

If we want to create 25 buttons, we can do it like this.

procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;

begin
For I := 1 to 25 do
TButton.Create(Self).Name := ‘MyButton ‘+IntToStr(I);
end;

But this code will not work very well? Where should it be placed? Who’s it’s parent? And – how can I access it again?

The answer is

FindComponent(const AName: String): TComponent

Since it’s returning a component, we must cast it over to a TButton:

The code is:

procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;

begin
For I := 1 to 25 do
begin
TButton.Create(Self).Name := ‘MyButton’+IntToStr(I);
With TButton(FindComponent(‘MyButton’+IntToStr(I))) do
begin
Parent := Self;       // Which is Form1
Top := I * 25 – 25;   // Place the first button to the top, the next one
Left := 0;            // 25 px under, and so an.
Height := 25;         // Standard size
Width := 75;          // Standard
end;
end;
end;

Now the button is created, but nothing happends if you press it. Hmmm… we need an event handler!

Let’s write an OnClick procedure.

First, declare it in the TForm’s declaration:

type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure MyButtonClick(Sender: TObject);  // Here!
private
{ Private declarations }
public
{ Public declarations }
end;

And… write it, just like you write any other handler. But, remember, this one will be invoked if you press any button! So it can be a good idea to find out which button the user pressed.

procedure TForm1.MyButtonClick(Sender: TObject);
begin
If (Sender is TButton) then    // Is it a button?
ShowMessage(‘You pressed ‘+(Sender as TButton).Caption);
end;

To make this code run, add this code below Width := 75:

OnClick := MyButtonClick;

Iklan
Kategori:Delphi
  1. Belum ada komentar.
  1. No trackbacks yet.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: