Easy way to find out which properties should be set when creating components at run time
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);
RunTimeLabel : TLabel;
// create RunTimeLabel
RunTimeLabel := TLabel.Create( Self );
with RunTimeLabel do
// 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!';
// RunTimeLabel will be
// automatically rleased when the
// form it's on (Form1) is freed.
// we don't have to manually free it
: Delphi code. Download runtime (0.46 KB)
That was easy enough. The real question is how do you find out exactly which properties (such as Top, Left, Width, etc., in the above example) has to be set at run time to get the effects you want. For example, if you drop a "TLabel" component on a form, you'll notice that there are more than 20 properties listed in the "Object Inspector". Do you have to set all those properties at run time if you create the component dynamically? The answer is no; most properties have default values, so you only have to set those properties that are required by the component and the ones you want to change. Well, except for the "Parent" property -- you must almost always set this property, usually to the form or component which your new component will be placed on or become a child of.
Here's an easy way to find out which properties you must set at run time:
- 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 end statement (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.
Applicable Keywords : Components, Delphi, Delphi 2.x, Delphi 3.x, Functions, Mini Tutorial, User Interface