One of the greatest strengths of Delphi is the ability to visually design the user interface of an application. This sometimes means that you would be creating most parts of your programs at design time rather than at run time as you go into different parts of your programs. Generally speaking, you can reduce the amount of memory required to run your program by creating memory hungry components at run time -- only when your application requires the functionality of those components. Here's a simple example on how to create components dynamically at run time (how to create a "TLabel" component at run time at 10,10 with the caption "hello, world"):
procedure TForm1.Button1Click(Sender: TObject);
var
RunTimeLabel : TLabel;
begin
//
// create RunTimeLabel
//
RunTimeLabel := TLabel.Create( Self );
with RunTimeLabel do
begin
//
// let RunTimeLabel know
// that it's owned by Form1
//
// Since this code is inside
// TForm1, Self refers to Form1
//
Parent := Self;
// customize the label
Left := 10;
Top := 10;
Width := 90;
Caption := 'hello, world!';
end;
//
// RunTimeLabel will be
// automatically rleased when the
// form it's on (Form1) is freed.
//
// we don't have to manually free it
//
end;
var
RunTimeLabel : TLabel;
begin
//
// create RunTimeLabel
//
RunTimeLabel := TLabel.Create( Self );
with RunTimeLabel do
begin
//
// let RunTimeLabel know
// that it's owned by Form1
//
// Since this code is inside
// TForm1, Self refers to Form1
//
Parent := Self;
// customize the label
Left := 10;
Top := 10;
Width := 90;
Caption := 'hello, world!';
end;
//
// RunTimeLabel will be
// automatically rleased when the
// form it's on (Form1) is freed.
//
// we don't have to manually free it
//
end;
Listing #1 : Delphi code. Download runtime (0.46 KB).
- Create the component you're interested in creating at runtime, during design time and customize it any way you want. For example, let's say you created a "TLabel" component called "RunTimeLabel"
- Right click on the form and select "View as Text"
- You'll see a line that reads:
object RunTimeLabel: TLabel
All properties and their values listed in between the above line and the very next endstatement (starting at the same tab position) are the properties you must set at run time, in order to recreate the component as you see it during the design time.